Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to loop over the child divs of a div and get the ids of the child divs?

I have a div with id test

and through the foreach loop I am creating some inner divs inside the test div. So it becomes like this.

<div id="test">
<div id="test-1"></div>
<div id="test-2"></div>
<div id="test-3"></div>
<div id="test-4"></div>
</div>

I am getting the parent div id "test" in the javascript function. Now I want to loop through the inner divs(child divs) of the test div and get the id of the each div one by one and style them through javascript.

Any Idea about this?

like image 959
Ahmad Avatar asked Jul 02 '12 09:07

Ahmad


2 Answers

Try this

var childDivs = document.getElementById('test').getElementsByTagName('div');

for( i=0; i< childDivs.length; i++ )
{
 var childDiv = childDivs[i];
}
like image 198
yogi Avatar answered Sep 18 '22 17:09

yogi


You can loop through inner divs using jQuery .each() function. The following example does this and for each inner div it gets the id attribute.

$('#test').find('div').each(function(){
    var innerDivId = $(this).attr('id');
});
like image 28
aaberg Avatar answered Sep 22 '22 17:09

aaberg