Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through divs inside a div

Tags:

javascript

dom

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.

like image 833
user977151 Avatar asked Dec 21 '22 01:12

user977151


1 Answers

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.

like image 187
Nick Beranek Avatar answered Jan 12 '23 14:01

Nick Beranek