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() ?
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() ?
Share Improve this question asked Jul 26, 2012 at 23:52 LINGSLINGS 3,6305 gold badges36 silver badges47 bronze badges 4 |2 Answers
Reset to default 14Plain 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');
You don't; you'd have to find all the <a>
tags that matched that criteria.
The .getElementById()
function is about getting an element by a unique "id" string. If you need to get elements otherwise, there are other APIs to use: .getElementsByTagName()
, .getElementsByClass()
, .querySelectorAll()
, etc. Browser support varies, and even .getElementById()
is different between IE and other browsers.
$('#menu li a').css('height', '10%');
Otherwise the necessary DOM traversal is much more complicated unless you only want to support modern browsers which have thequerySelectorAll
method. – ThiefMaster Commented Jul 26, 2012 at 23:54