Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change CSS with javascript using 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() ?

like image 609
LINGS Avatar asked Jul 26 '12 23:07

LINGS


People also ask

Can you change CSS with JavaScript?

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.

Can JavaScript change the style of an HTML element?

The HTML DOM allows JavaScript to change the style of HTML elements.


1 Answers

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');
like image 152
Michael Berkowski Avatar answered Oct 07 '22 02:10

Michael Berkowski