Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
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 Respostas
Responde à pergunta

0

Try the following:

.getSelection().getRangeAt(0).startContainer.nodeName
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda