使用 getElementById 使用 javascript 更改 CSS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11679679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change CSS with javascript using getElementById
提问by LINGS
I do not know how to access a specific CSS using javascript.
我不知道如何使用 javascript 访问特定的 CSS。
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() ?
如何使用 document.getElementById() 访问它?
回答by Michael Berkowski
Plain JavaScript solution:
纯 JavaScript 解决方案:
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
:
您不能getElementById()
在这种情况下使用,因为它的目的只是查询 id 属性,但您可以getElementsByTagName()
在以下上下文中使用#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:
jQuery 解决方案:
If you are able to use jQuery, this becomes exceedingly simpler:
如果您能够使用 jQuery,这将变得非常简单:
$('#menu li a').css('color', 'blue');
回答by Pointy
You don't; you'd have to find all the <a>
tags that matched that criteria.
你没有;您必须找到<a>
符合该条件的所有标签。
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.
该.getElementById()
函数是关于通过唯一的“id”字符串获取元素。如果你需要得到的元素,否则,也有其他的API来使用:.getElementsByTagName()
,.getElementsByClass()
,.querySelectorAll()
等浏览器支持不同而不同,甚至.getElementById()
是IE和其他浏览器之间的不同。