Search code examples
javascriptrangy

Getting the parent node for selected text with rangy library


I'm using the rangy library and can select text in a content editable as follows:

var sel = rangy.getSelection();
alert(sel);

I can't figure out how to get the selected text parent node/element. For example, if I'm selecting text that is

<strong>My Text</strong> 
or
<h1>My Title</h1>

how can I include the strong node or H1 element also?


Solution

  • sel.anchorNode.parentNode will get you the parent node of the node containing only one end of the selection. To get the innermost containing element for the whole selection, the easiest thing is to get a Range from the selection and look at its commonAncestorContainer property (which may be a text node, in which case you need to get its parent):

    var sel = rangy.getSelection();
    if (sel.rangeCount > 0) {
        var range = sel.getRangeAt(0);
        var parentElement = range.commonAncestorContainer;
        if (parentElement.nodeType == 3) {
            parentElement = parentElement.parentNode;
        }
    }