javascriptnodelistchild-nodes

How to use for loop through childNodes?


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

Solution

  • 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>