Skip to content Skip to sidebar Skip to footer

How Can I Tell The Owner Of A Selection?

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

Solution 1:

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:

functiongetSelectionContainerElement() {
    var container = null;
    if (typeofwindow.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            container = sel.getRangeAt(0).commonAncestorContainer;
            if (container.nodeType != 1) {
                container = container.parentNode;
            }
        }
    } elseif (typeofdocument.selection != "undefined" && document.selection.type != "Control") {
        container = document.selection.createRange().parentElement();
    }
    return container;
}

Solution 2:

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

Post a Comment for "How Can I Tell The Owner Of A Selection?"