0

How can I tell who the parent node of a selection is?

I'm getting a selection with:

        var userSelection;
        if (window.getSelection) {
            userSelection = window.getSelection();
        }
        else if (document.selection) { 
            userSelection = document.selection.createRange();
        }

        var selectedText = userSelection;
        if (userSelection.text)
            selectedText = userSelection.text;

But how can i tell who's the parent node of the selection? That is, if the whole selection is from withing a single div I want to know that div.

Justin808
  • 20,859
  • 46
  • 160
  • 265
  • possible duplicate of [How can I check the node of the selection using Range object in javascript ?](http://stackoverflow.com/questions/4204822/how-can-i-check-the-node-of-the-selection-using-range-object-in-javascript) – Andrew Marshall Mar 28 '11 at 23:44

2 Answers2

0

Try $(':contains(' + selectedText + ')').parent(). Does that work?

GregL
  • 37,147
  • 8
  • 62
  • 67
  • 1
    True, but if all you have is the selected text, with no context, how else are you going to locate it on the page? – GregL Mar 29 '11 at 00:04
0

The following will return the parent element of the selection in all major browsers, with the following caveats:

  • Getting the parent node instead (which could be of any type but is most commonly a text node) is easy on most browsers but tricky in IE < 9. If you need to do this, there are libraries such as my own Rangy that provide DOM Range and Selection support for all major browsers.
  • The function below only considers the first Range within the selection. Firefox is the only major browser that supports multiple selections; only the first is considered.

Code:

function getSelectionContainerElement() {
    var container = null;
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            container = sel.getRangeAt(0).commonAncestorContainer;
            if (container.nodeType != 1) {
                container = container.parentNode;
            }
        }
    } else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
        container = document.selection.createRange().parentElement();
    }
    return container;
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536