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>

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?



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.

    var innerDivId = $(this).attr('id');

Try this

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

for( i=0; i< childDivs.length; i++ )
 var childDiv = childDivs[i];

Here's the solution if somebody still looks for it

function getDivChildren(containerId, elementsId) {
    var div = document.getElementById(containerId),
        subDiv = div.getElementsByTagName('div'),
        myArray = [];

    for(var i = 0; i < subDiv.length; i++) {
        var elem = subDiv[i];
        if( === 0) {
    return myArray;
console.log(getDivChildren('test', 'test-'));

You can use


and each()

this way for example :

    var atId =;
    // do something with it

What you are trying to do is loop through the direct-descendant divs of the #test div; you would do this using the > descendant selector, and the jQuery .each() iterator. You can also use the jQuery .css() and .attr() methods for styling and retrieving the id respectively.

$("#test > div").each(function(index){
    var id = $(this).attr("id");
    $(this).css(/* apply styles */);

Use jQuery.

This code can be addapted to your needs:

$testDiv = ?$('div#test')????????????.first();    
$('div', $testDiv).css("margin", '50px');????


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.