Changing CSS using javascript with getElementById

I don't know how to access specific CSS using javascript.

Let's say

#menu { color: red; }

can access

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

But I want to access

#menu li a { height: 10%; }

How to access this using document.getElementById ()?

+5
source share
2 answers

Equal JavaScript Solution:

You cannot use getElementById()in this case, since its purpose is only to request identifier attributes, but you can use getElementsByTagName()in context #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 can use jQuery, this becomes extremely simple:

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

; <a>, .

.getElementById() - "id". , API: .getElementsByTagName(), .getElementsByClass(), .querySelectorAll() .. , .getElementById() IE .

+2

All Articles