简体   繁体   English

如何使用for循环遍历子节点?

[英]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).我需要在 div 内的每个节点(第一个节点 - 1、第二个 - 2 等)上动态设置 z-index。 When I'm trying to use the "for" loop on childNodes, I got an error "Uncaught TypeError: Cannot set property 'zIndex' of undefined".当我尝试在子节点上使用“for”循环时,出现错误“Uncaught TypeError: Cannot set property 'zIndex' of undefined”。 Can you please point out my mistake?你能指出我的错误吗?

You can see the codepen: https://codepen.io/pen/可以看到codepen: https://codepen.io/pen/

HTML + JS: HTML + 记者:

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

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>

Set the z-index using .style and the iteration of i on each of your elements in your loop.在循环中的每个元素上使用.stylei的迭代设置 z-index。 Example below in snippit...下面的示例在 snippit 中...

images[i].style.zIndex = i; will do the trick.会成功的。 I have selected the elements directly using the classname, no need for childNode ...我直接使用类名选择了元素,不需要childNode ...

You can open your browsers console and check the CSS properties for each node after you run the code.运行代码后,您可以打开浏览器控制台并检查每个节点的 CSS 属性。

Console for the snippit below once run:运行后以下代码片段的控制台: 在此处输入图像描述

 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>

You can loop over the structure like this.您可以像这样遍历结构。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM