11

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

4
  • 4
    Is jQuery an option? If yes: $('#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 the querySelectorAll method. Commented Jul 26, 2012 at 23:54
  • 2
    Do you want it to affect any future elements? Or just those that exist at the time where your code runs? Commented Jul 26, 2012 at 23:55
  • @ThiefMaster only when the code runs. I could use Jquery, so things are very simple. thanks! Commented Jul 27, 2012 at 0:03
  • 1
    @LINGS: If you don't have much JavaScript on your page, there's a very good chance that loading jQuery will be overkill. The jQuery zealots rarely mention that. Commented Jul 27, 2012 at 0:10

2 Answers 2

14

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');
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.