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.parentNodewill 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 itscommonAncestorContainerproperty (which may be a text node, in which case you need to get its parent):