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?
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?
Share Improve this question edited May 12, 2012 at 10:36 skaffman 404k96 gold badges824 silver badges775 bronze badges asked May 12, 2012 at 0:43 FrankFrank 7141 gold badge9 silver badges21 bronze badges 1- 1 Messing around some more I see that I can use: sel.anchorNode.parentNode.nodeName – Frank Commented May 12, 2012 at 1:10
1 Answer
Reset to default 8sel.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 monAncestorContainer
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.monAncestorContainer;
if (parentElement.nodeType == 3) {
parentElement = parentElement.parentNode;
}
}