最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to select all text in <p> tag? - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 6

Your 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

发布评论

评论列表(0)

  1. 暂无评论