开发者

nodeName for selected text in Javascript

开发者 https://www.devze.com 2023-01-17 23:31 出处:网络
I have HTML which looks something like this: <span id=\"text\"> <span class=\"segment\" id=\"first\">some text</span>

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.nodeNa开发者_开发知识库me;
    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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号