Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
104
rated 0 times [  108] [ 4]  / answers: 1 / hits: 52165  / 12 Years ago, thu, july 26, 2012, 12:00:00

I do not know how to access a specific CSS using javascript.



Let us say,



#menu { color: red; }


can be accessed by



document.getElementById('menu').style.color = blue;


But I want to access



#menu li a { height: 10%; }


How do I access that using document.getElementById() ?


More From » html

 Answers
36

Plain JavaScript solution:



You cannot use getElementById() in this case since its purpose is only to query id attributes, but you can use getElementsByTagName() in context of #menu:



var m = document.getElementById('menu');
// Get all <li> children of #menu
var lis = m.getElementsByTagName('li');
// Loop over them
for (var i=0; i<lis.length; i++) {
// Get all <a> children of each <li>
var atags = lis[i].getElementsByTagName('a');
for (var a = 0; a<atags.length; a++) {
// And set their color in a loop.
atags[a].style.color = 'blue';
// or change some other property
atags[a].style.height = '25%';
}
}


jQuery Solution:



If you are able to use jQuery, this becomes exceedingly simpler:



$('#menu li a').css('color', 'blue');

[#84031] Tuesday, July 24, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
laytonlamontm

Total Points: 745
Total Questions: 130
Total Answers: 130

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
;