Reputation: 183
Lets say we have this code:
<div id='m1'>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
</div>
<div id='m2'>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
</div>
How can i get divs with class 'c' that are in div with id 'm1'? And then set them some css settings...
Upvotes: 0
Views: 2803
Reputation: 12412
With jQuery you could do something like this:
$('#m1 > .c').css('color', 'red');
You could also do it with pure JavaScript by using document.querySelectorAll('#m1 > .c')
and then looping through each item in the returned node collection and use element.setAttribute('color', 'red')
Upvotes: 0
Reputation: 4075
This function from here will fetch an array of all the elements under a particular tag that have a certain class ID.
function getElementsByClassName(classname, node) {
if(!node) node = document.getElementsByTagName("body")[0];
var a = [];
var re = new RegExp('\\b' + classname + '\\b');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;
}
So your code would be:
elementsInM1 = getElementsByClassName('c', 'm1');
if( elementsInM1.length > 0 )
{
// Loop through, apply styles as you would to normal elements
// returned by getElementByID
}
Upvotes: 0
Reputation: 2795
var m1Div = document.getElementById("m1");
var cDivs = m1Div.getElementsByClassName("c");
for(i = 0; i < cDivs.length; i++)
{
//apply css attributes to cDivs[i]
}
Upvotes: 0
Reputation: 98489
div#m1 div.c {
/* Properties here ... */
}
This will apply the properties to all class="c"
div
s within a div
which itself has id="m1"
.
If you're asking for how to get them with Javascript, you can use any library that bundles a CSS-type selector library (like Sizzle!) to do this easily.
For example, in JQuery:
$("div#m1 div.c").style(/* something */);
Or in Dojo:
dojo.style(dojo.query("div#m1 div.c"), /* something */);
Upvotes: 2