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

144
Vistas
Is there a better way targeting the last element child of previous sibling

I mean the code does work, but at some point, it seems a bit weird to me, so I was wondering if someone does know a better way of targeting the last element child of the previous element sibling.

Basically, I have a slider which value I want to show with the span of its previous sibling, example:

<div class="xOffsetBox">
  <label for="xOffset" class="xOffsetText">xOffset <span>0 px</span></label>
  <input type="range" name="xOffset" id="xOffsetRange1" min="-100" max="100" value="0">
</div>

And, within a js function, I get the value of the range input.

function getRangeValue () {

for (let i = 0; i < Shadows.length; i++) {
 let xOffset = document.getElementById(Shadows[i].xOffsetValue).value;
 let xOffsetSpan = document.getElementById(Shadows[i].xOffsetValue).previousElementSibling.lastElementChild;
 xOffsetSpan.textContent = xOffset + " px";
};
    };
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I'd probably use data-attributes they are quite useful. They don't pollute your css-class-attribute and it is not unique like id. Also, it is fairly easy to scale up.

There is not much you can do here with your query, since you try to work with a sibling.

The question is also: What are you trying to achieve here? What is "better" in your own words? Is it the lines of code, you want to reduce, reduce the complexity, or to find an alternative way? You could use an id, a class, or even a data-attribute on that sibling and just access it with document.querySelector or for id-lookup: document.getElementById. It really depends on what you try to accomplish.

You could, maybe, optimize it like this:

for (let i = 0; i < Shadows.length; i++) {
  const el = document.getElementById(Shadows[i].xOffsetValue);
  const xOffset = el.value;
  const xOffsetSpan = el.previousElementSibling.lastElementChild;
  xOffsetSpan.textContent = xOffset + " px";
};

This way you don't have to travel the DOM twice to find the element. You can also use const instead of let, if you don't want to modify these values. Maybe even use a for-of iterator instead, if you like.

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