rangy icon indicating copy to clipboard operation
rangy copied to clipboard

How can I determine if the selected text is wrapped in an element?

Open brandondurham opened this issue 10 years ago • 2 comments

I'm working on a small plugin that, at its base level, just wraps the selected text in a <span> tag and applies inline styles to it. What I need to do is detect if the selected text is already wrapped in a <span> (or any other element that can have styles applied) and just apply the style attribute to that element. Thing is, when checking to see if its already wrapped I need to ensure that the parent element contains only the selected text, and that the styles won't be applied to surrounding text.

Is there a simple way to check the selection to see if it is already wrapped by an element that I can use, and that this element contains only the text that is selected?

brandondurham avatar Jul 21 '15 17:07 brandondurham

If I understand you correctly, I think the answer is "not really". You can get the parent element for the selected range easily enough:

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

You can check whether the range contains all of the text within the parent element with containsNodeText, a Rangy-specific convenience method:

if (range.containsNodeText(parentElement)) {
  // Do stuff
}

Beyond that, you're on your own. I spent a while a few years ago writing on a module for applying arbitrary styles but it got too complicated and I abandoned it.

timdown avatar Jul 21 '15 23:07 timdown

In 2019, any way to accomplish this? I would need the same thing for a summernote plugin.

msqar avatar Aug 21 '19 15:08 msqar