最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Change CSS with javascript using getElementById - Stack Overflow

programmeradmin4浏览0评论

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

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

Share Improve this question asked Jul 26, 2012 at 23:52 LINGSLINGS 3,6305 gold badges36 silver badges47 bronze badges 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. – ThiefMaster 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? – ThiefMaster Commented Jul 26, 2012 at 23:55
  • @ThiefMaster only when the code runs. I could use Jquery, so things are very simple. thanks! – LINGS 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. – user1106925 Commented Jul 27, 2012 at 0:10
Add a comment  | 

2 Answers 2

Reset to default 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');

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.

发布评论

评论列表(0)

  1. 暂无评论