LIN*_*NGS 8 html javascript css getelementbyid
我不知道如何使用javascript访问特定的CSS.
让我们说,
#menu { color: red; }
Run Code Online (Sandbox Code Playgroud)
可以访问
document.getElementById('menu').style.color = "blue";
Run Code Online (Sandbox Code Playgroud)
但我想访问
#menu li a { height: 10%; }
Run Code Online (Sandbox Code Playgroud)
如何使用document.getElementById()访问它?
Mic*_*ski 10
您不能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%';
}
}
Run Code Online (Sandbox Code Playgroud)
如果你能够使用jQuery,这变得非常简单:
$('#menu li a').css('color', 'blue');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33893 次 |
| 最近记录: |