0

How can I determine the node (what tag this innerHTML is associated with) that is associated with a given javascript selection object? I am using window.getSelection() and would like to know in which div/span class the selection is in.

Thank you!

joshim5
  • 2,292
  • 4
  • 28
  • 40
  • possible duplicate of [How do I find out which Javascript element has focus?](http://stackoverflow.com/questions/497094/how-do-i-find-out-which-javascript-element-has-focus) – Marc B Aug 05 '11 at 20:29

1 Answers1

1

If you want the deepest element that contains the whole of the selection, the easiest way is to obtain a Range object from the selection and use its commonAncestorContainer property.

jsFiddle: http://jsfiddle.net/5LvEG/1/

Code:

function getSelectionContainerElementId() {
    var sel = window.getSelection();
    if (sel.rangeCount > 0) {
        var range = sel.getRangeAt(0);
        var container = range.commonAncestorContainer;

        // container could be a text node, so use its parent if so
        if (container.nodeType == 3) {
            container = container.parentNode;
        }
        return container.id;
    }
    return null;
}

alert(getSelectionContainerElementId());
Tim Down
  • 318,141
  • 75
  • 454
  • 536