views:

30

answers:

1

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);
    }
+1  A: 

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.

Tim Down