Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!