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?

Answers:

Answer

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');
});
Answer

Try this

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

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

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-'));
Answer

You can use

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

and each()

this way for example :

$('[id^=test-]').each(function(){
    var atId = this.id;
    // do something with it
});?
Answer

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 */);
});
Answer

Use jQuery.

This code can be addapted to your needs:

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.