javascript 循环遍历 div 内的 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9468807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:46:47  来源:igfitidea点击:

loop through divs inside a div

javascriptdom

提问by user977151

I need an idea on how to start a loop where I can get the innerHTML for the 3 divs inside a div:

我需要一个关于如何开始循环的想法,我可以在其中获取 div 中 3 个 div 的 innerHTML:

<div id="hi">
 <div> Item1 </div>
 <div> Item2 </div>
 <div> Item3 </div>
</div>

I need to make a function that search through the item list and see for common items. I know one way is to use document.getElementsByTagNamebut I don't need to see the innerHTML for each div.

我需要创建一个功能来搜索项目列表并查看常见项目。我知道一种方法是使用,document.getElementsByTagName但我不需要查看每个 div 的 innerHTML。

回答by Nick Beranek

Since getElementsByTagName()returns an array, you can use a forloop for each of the elements.

由于getElementsByTagName()返回一个数组,您可以for对每个元素使用一个循环。

var div = document.getElementById('hi'):
var divs = div.getElementsByTagName('div');
var divArray = [];
for (var i = 0; i < divs.length; i += 1) {
  divArray.push(divs[i].innerHTML);
}

This will push the innerHTMLof each of the elements into the divArrayvariable.

这会将innerHTML每个元素的推入divArray变量中。