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() ?
JavaScript can change Css styles such as color, font size etc. of elements using some methods such as getElementById(), getElementByClassName() etc. In the following example font style and font size of the elements have changed using getElementById() method.
The HTML DOM allows JavaScript to change the style of HTML elements.
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%';
}
}
If you are able to use jQuery, this becomes exceedingly simpler:
$('#menu li a').css('color', 'blue');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With