Change CSS with javascript using getElementById

LINGS picture LINGS · Jul 27, 2012 · Viewed 38.5k times · Source

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() ?

Answer

Michael Berkowski picture Michael Berkowski · Jul 27, 2012

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');