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";
};
};
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.