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

127
Visualizações
Set cursor position to 0 in inline node in HTML editable content

In an editableContent div I want the user to type something within an inline element. Therefore, when the cursor is within this inline element, and the user uses the left arrow key, the cursor should jump to position 0 WITHIN the inline element.

Here is an example:

document.querySelector("#editable").addEventListener("keydown", (e) => {
  const keys = ["ArrowLeft", "ArrowRight"]
  if (keys.includes(e.code)) {
    // handle event

    const selection = document.getSelection()
    if (!selection || !selection.anchorNode) {
      return
    }
    if (selection.anchorNode.parentElement.nodeName !== "MARK") {
      return
    }

    e.preventDefault()

    const setOffset = offset => {      
      const range = document.createRange()
      range.collapse()
      range.setStart(selection.anchorNode, offset)
      
      selection.removeAllRanges()
      selection.addRange(range)
    }



    if (e.code === keys[0]) {
      setOffset(0)

    }

    if (e.code === keys[1]) {
      setOffset(selection.anchorNode.textContent.length)
    }
  }

})
#editable {
  border: 1px solid black;
  padding: 10px;
}
<div id="editable" contentEditable>
  Here is some <mark>text</mark> for testing!
</div>

The problem is that setOffset(0) sets the cursor before the <mark> tag and typing there makes the text appear not within the <mark> tag.

On the other side using the right arrow and setting the cursor to the last element setOffset(selection.anchorNode.textContent.length) works as expected (typing there extends the mark tag).

Is there a trick to set the cursor to position 0 within the inline element?

about 4 years ago · Juan Pablo Isaza
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