Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try the following:

.getSelection().getRangeAt(0).startContainer.nodeName
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!