最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - loop through divs inside a div - Stack Overflow

programmeradmin3浏览0评论

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

<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.getElementsByTagName but I don't need to see the innerHTML for each div.

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

<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.getElementsByTagName but I don't need to see the innerHTML for each div.

Share Improve this question edited Nov 2, 2012 at 9:35 johannes 7,2725 gold badges40 silver badges57 bronze badges asked Feb 27, 2012 at 16:48 user977151user977151 5055 gold badges9 silver badges18 bronze badges 4
  • 3 I don't need to see the innerHTML for each div I thought the innerHTML is exactly what you want to get? Have you had a look at some documentation? What have you tried so far? document.getElementsByTagName is a good start, what exactly are you having problems with now? Obviously we won't do your homework... – Felix Kling Commented Feb 27, 2012 at 16:51
  • Other than pasting his assignment into the SO question box, it doesn't look like he's actually tried anything. – James M Commented Feb 27, 2012 at 16:54
  • Please explain what you are trying to do, "see for common items" doesn't explain it well. – Ben Commented Feb 27, 2012 at 16:56
  • you want to IDENTIFY the ones with duplicate values? Or you want to strip the extra duplicate value? I'm confused.. – Downpour046 Commented Feb 27, 2012 at 16:57
Add a comment  | 

1 Answer 1

Reset to default 15

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

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 innerHTML of each of the elements into the divArray variable and iterate through them.

发布评论

评论列表(0)

  1. 暂无评论