I need to set z-index dynamically on every node inside div (first node - 1, second - 2, etc). When I'm trying to use the "for" loop on childNodes, I got an error "Uncaught TypeError: Cannot set property 'zIndex' of undefined". Can you please point out my mistake?
You can see the codepen: https://codepen.io/pen/
HTML + JS:
<div id="blog__images" class="blog__images">
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
<div class="image"></div>
</div>
var images = document.getElementById('blog__images').childNodes;
for (var i = 1; i < images.length; ++i) {
images[i].style.zIndex = i;
}
childNodes
includes the (empty) text nodes between elements. Use.children
instead. – Niet the Dark Absolconsole.log(images[i])
would have revealed this problem immediately – Niet the Dark Absolfor (const child of node.childNodes) { child.style.zIndex = ... }
is a lot easier to read/write than using a numerical index,i
. Read more about for..of syntax – Mulan