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

218
Vistas
HTML's Selection object returning the wrong node

It's important for me to know the difference between clicking before one letter versus after the previous, even though both cases might look the same on screen. This is because the meaning can be carried through the number of spans that are nested. An example:

<span id="x-container"><span id="x">x</span></span><span id="y">y</span>

<script>
  document.addEventListener('selectionchange', e => {
    var selection = window.getSelection();
    if (selection.type =='Caret')
      console.log(selection.anchorNode.textContent,selection.anchorOffset)
  })
</script>

The console.log()s look as follows:

clicking on the x slightly left-of-center, we get x 0 (correct)

clicking on the x slightly right-of-center, we get x 1 (correct)

clicking on the y slightly left-of-center, we get x 1 again: WRONG!!!!

clicking on the y slightly right-of-center, we get y 1 (correct)

How can I fix this third case so I can tell whether we clicked before y versus after x? I tried adding a dummy span between the two but it didn't work.

Note that the x and y look a little close to each other here. In the actual thing I'm doing, I'm adding padding so it doesn't look as strange and is easier to click before y vs after x. Just take my word for it that adding padding/margin doesn't change the problem...

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Since you are only interested in the selectionchange events that were triggered by a mouse event, you can check which element received the mousedown event that did trigger this selectionchange event.
You just have to store it in a variable accessible to your selectionchange handler, then if it's not the Selection's anchorNode, or doesn't contain it, you know that the browser messed up.
You then have to check if the actual target was before or after to correctly find the new anchorOffset:

let activeElem = null;
document.addEventListener('selectionchange', e => {
  const selection = window.getSelection();
  let { anchorNode, anchorOffset } = selection;
  if (anchorNode === selection.focusNode) {
    if (activeElem && (!activeElem.contains(anchorNode))) {
      const isBefore = activeElem.nextElementSibling.contains(anchorNode);
      anchorOffset = isBefore ? activeElem.textContent.length : 0;
      anchorNode = activeElem;
    }
    console.log(anchorNode.textContent, anchorOffset);
  }
})
document.addEventListener("mousedown", e =>
  // here you can change the selector from "span" to anything more restrictive
  // as long as it matches your "targetted" elements
  activeElem = e.target.matches("span") ? e.target : null
);
document.addEventListener("mouseup", e => activeElem = null);
<span id="x">x</span><span id="b">b</span>

about 4 years ago · Santiago Trujillo Denunciar
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