JavaScript – How to determine if there is no HTML element around the selected text.

I am implementing a simple text editor with content editable div and two buttons, one for bold text and one for italics. The way I make the text bold or italic is by inserting a span Around the selected text with the class text-bold And text-italicRespectively, and then do styles using CSS. However, I do not want to add span Inside a span To make the text bold And Like a slant

<span class="text-bold">
   <span class="text-italic">Some Text</span>
</span>

But when I select a text I want to see if it is already surrounded by a. span, And if so, add a class to show the desired change. For example, suppose I already have.

<p>Hello there
   <span class="text-bold">
      Some Text
   </span>
</p>

Later in the DOM if I want to create. Some Text In italics, I only add classes. text-italic Such

<p>Hello there
   <span class="text-bold text-italic">
      Some Text
   </span>
</p>

I know it selection.anchorNode.parentNode Will return containing p Tags, and selection.anchorOffset Will return offset from p In the characters but I’m not sure how to use that data to get back around. span

Write a Comment