简体   繁体   中英

Is there a way to select text through multiple elements?

 var range = document.createRange(); var root_node = document.getElementById("test"); // Start at the `hello` element. range.setStart(root_node.childNodes[0], 2); // End in the `world` node range.setEnd(root_node.childNodes[1], 2); range.selectNodeContents(root_node); let sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range);
 <div id="test"> <a href="#">hello</a> <span>world</span> </div>

I'd like to select text but because it's in different elements it hasn't been working. Is there a way to do this?

I don't mean to highlight both words in their entirety but portions of each word.

@Matt answer is in the right direction, but doesn't achieve what the OP wants, which is to "span" the range across multiple elements (nodes), while using offsets within those elements.

The following achieve it:

 var range = document.createRange(); var root_node = document.getElementById("test"); range.setStart(root_node.querySelector('a').firstChild, 2); range.setEnd(root_node.querySelector('span').firstChild, 3); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range);
 <div id="test"> <a href="#">hello</a> <span>world</span> </div>

Note how on both setStart and setEnd we pass a text node - this is the firstChild of the anchor and span elements.

For further reading on this subject, please refer to this excellent explanation .

You called setStart twice, instead of setStart followed by setEnd , and you are specifying an offset of 2 in each case, but I don't think you want an offset because that puts your node index out of range (and throws an error).

 var range = document.createRange(); var root_node = document.getElementById("test"); // Start at the `hello` element. range.setStart(root_node.childNodes[0], 0); // End in the `world` node range.setEnd(root_node.childNodes[1], 0); range.selectNodeContents(root_node); let sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range);
 <div id="test"> <a href="#">hello</a> <span>world</span> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM