I want to make button, which will select all text in my p tag. Example of tag:
<p class="foo">
some text
<div>this div is child of p</div>
<div>one more row</div>
</p>
Also solution must be via window.getSelection() or similar but not jQuery. I am trying do this by using selectNodeContents(el), but result was only first line.
Can anyone help me, because I can't figure this out.
edit code:
var selection = window.getSelection();
var txt = document.getElementsByClassName("foo");
var range = document.createRange();
range.selectNodeContents(txt);
selection.removeAllRanges();
selection.addRange(range);
I want to make button, which will select all text in my p tag. Example of tag:
<p class="foo">
some text
<div>this div is child of p</div>
<div>one more row</div>
</p>
Also solution must be via window.getSelection() or similar but not jQuery. I am trying do this by using selectNodeContents(el), but result was only first line.
Can anyone help me, because I can't figure this out.
edit code:
var selection = window.getSelection();
var txt = document.getElementsByClassName("foo");
var range = document.createRange();
range.selectNodeContents(txt);
selection.removeAllRanges();
selection.addRange(range);
Share
Improve this question
edited Nov 6, 2014 at 20:34
Pointy
414k62 gold badges595 silver badges629 bronze badges
asked Nov 6, 2014 at 20:27
RomanRoman
532 silver badges8 bronze badges
1
- 4 You should post the code you've tried so far. – Pointy Commented Nov 6, 2014 at 20:29
2 Answers
Reset to default 6Your basic problem is, I think, that <div>
elements cannot be children of <p>
elements. Your <p>
implicitly ends at the opening of the first <div>
.
If you change the <div>
elements to <span>
then they'll be inside the <p>
. The next problem you'll have to fix is that .getElementsByClassName()
returns a node list, not a single element, so the code has to take that into account:
range.selectNodeContents(txt[0]);
Here is a working CodePen.
You will need to structure your HTML better as nested a <div>
inside a <p>
is invalid but:
http://jsfiddle/hge2Lp0p/1/
Using answer from: Select text in javascript