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.
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');
});
You can use
$('[id^=test-]')
and each()
this way for example :
$('[id^=test-]').each(function(){
var atId = this.id;
// 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 */);
});
Try this
var childDivs = document.getElementById('test').getElementsByTagName('div');
for( i=0; i< childDivs.length; i++ )
{
var childDiv = childDivs[i];
}
Use jQuery.
This code can be addapted to your needs:
$testDiv = $('div#test').first();
$('div', $testDiv).css("margin", '50px');
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-'));