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?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With