'How to find out if a selected text is surrounded by an html element of not
I am implementing a simple text editor with content editable div and a two buttons, one for bold text and one for italic. The way I am making a text bold or italic is by inserting a span
around the selected text with class text-bold
and text-italic
, respectively, and then do the styles using css. However, I don't want to keep adding span
inside a span
to make a text bold and italic like
<span class="text-bold">
<span class="text-italic">Some Text</span>
</span>
but rather when I select a text, I want to check if it's already surrounded with a span
, and if yes, then add a class to it to reflect the desired change. For example, suppose I already have
<p>Hello there
<span class="text-bold">
Some Text
</span>
</p>
in the DOM. Later if I want to make Some Text
in italic, I just add the class text-italic
like so
<p>Hello there
<span class="text-bold text-italic">
Some Text
</span>
</p>
I know that selection.anchorNode.parentNode
will return the containing p
tag, and selection.anchorOffset
will return the offset from p
in characters. But I am not sure how to use these data to return the surrounding span
.
So, my question is: how can I return the surrounding html element with its attributes if exists of a selected text?
Solution 1:[1]
Try the following:
.getSelection().getRangeAt(0).startContainer.nodeName
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Zach Jensz |