Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda