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

354
Visualizações
On selecting text from HTML paragraph using window.getSelection(), the range index value is giving 0 when text from different/child tag is selected

I am trying select text from a HTML paragraph and get the index range.

To get the range values, i'm using the below code

{
startIndex = window.getSelection().getRangeAt(0).startOffset;
endIndex = window.getSelection().getRangeAt(0).endOffset;
}

Below is the HTML paragraph.

<p>Pellentesque <b>habitant</b> morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>

Now when i select the word "habitant" the startOffset() is returning 0 as a new/child tag started but i need the index starting from the paragraph

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It returns 0 because the work "habitant" is wrapped inside another node so the anchor node won't be the hall paragraph it'll be just the node <b>haitant</b> you can either fix this by removing the tag <b>.

<p class="text">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>

another workaround will be to search for the selected word inside the parent node

<p class="text">Pellentesque <b>habitant</b> morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>



const getSelectedTextIndex = () => {
    const selectedText = window.getSelection().toString()
    startIndex = document.querySelector('.text').innerText.indexOf(selectedText)
    endIndex = startIndex + selectedText.length
}
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