简体   繁体   中英

nodeName for selected text in Javascript

I have HTML which looks something like this:

<span id="text">
 <span class="segment" id="first">some text</span>
 <span class="segment" id="sec">bla bla</span>
</span>

and when user selects something, I want to identify which elements he had selected. If, for example, user had selected "text bl" I need both "first" and "sec" elements.

For this, I tried using endContainer.nodeName but for every selected text I get parent element "text". Is it posible to get child elements?

var selObj = window.getSelection();
    var selRange = selObj.getRangeAt(0);
    if(selRange!="") {
    var startName = selRange.startContainer.nodeName;
    var endName = selRange.endContainer.nodeName;
    alert(startName+" "+endName);
    }

In your example, the problem is that the start and end container nodes for the selection are text nodes. You can get the container elements by checking the nodeType property:

var startNode = selRange.startContainer;
if (startNode.nodeType == 3) { // 3 is the node type for text nodes
    startNode = startNode.parentNode;
}

... and similar for the end container.

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