19

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?

Ahmad
  • 2,099
  • 10
  • 42
  • 79

6 Answers6

38

Try this

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

for( i=0; i< childDivs.length; i++ )
{
 var childDiv = childDivs[i];
}
yogi
  • 19,175
  • 13
  • 62
  • 92
11

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');
});
Andreas
  • 5,393
  • 9
  • 44
  • 53
aaberg
  • 2,253
  • 15
  • 14
5

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(elem.id.indexOf(elementsId) === 0) {
            myArray.push(elem.id);
        }
    }
    return myArray;
}
console.log(getDivChildren('test', 'test-'));
lesandru
  • 839
  • 2
  • 11
  • 27
0

You can use

$('[id^=test-]')

and each()

this way for example :

$('[id^=test-]').each(function(){
    var atId = this.id;
    // do something with it
});​
Shikiryu
  • 10,180
  • 8
  • 49
  • 75
0

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 */);
});
nbrooks
  • 18,126
  • 5
  • 54
  • 66
-1

Use jQuery.

This code can be addapted to your needs:

$testDiv = ​$('div#test')​​​​​​​​​​​​.first();    
$('div', $testDiv).css("margin", '50px');​​​​
Hooch
  • 28,817
  • 29
  • 102
  • 161