0
votes

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;
}
3
childNodes includes the (empty) text nodes between elements. Use .children instead.Niet the Dark Absol
And FYI, console.log(images[i]) would have revealed this problem immediatelyNiet the Dark Absol
for (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 syntaxMulan

3 Answers

0
votes

Whitespace inside elements is considered as text, and text is considered as nodes. Those text nodes should be skipped.

var images = document.getElementById('blog__images').childNodes;
// console.log(images);
for (var i = 1; i < images.length; ++i) {
    if (images[i] && images[i].nodeType != 3) {
      console.log("My node:" + images[i].nodeName);
      images[i].style.zIndex = i;
     } else {
      console.log("Skipping Extra node:" + images[i].nodeName);
     }
}
<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>
0
votes

Set the z-index using .style and the iteration of i on each of your elements in your loop. Example below in snippit...

images[i].style.zIndex = i; will do the trick. I have selected the elements directly using the classname, no need for childNode...

You can open your browsers console and check the CSS properties for each node after you run the code.

Console for the snippit below once run: enter image description here

let images = document.getElementsByClassName('image');
let imgZIndex;
for(let i = 0; i < images.length; i++){
imgZIndex = images[i].style.zIndex = i;
console.log(imgZIndex)
}
<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>
0
votes

You can loop over the structure like this.

var images = document.getElementById('blog__images').childNodes;
for (var img : images) {
    images[img].style.zIndex = img;
}