Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 392
Frank Avatar asked May 12 '12 00:05

Frank


1 Answers

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;
    }
}
like image 70
Tim Down Avatar answered Nov 01 '22 04:11

Tim Down