You can use querySelector
(IE7 and lower not supported):
document.querySelector("ul > li")
Or querySelectorAll
:
document.querySelectorAll("ul > li")[0]
Or getElementsByTagName
:
document.getElementsByTagName("ul")[0]
.getElementsByTagName("li")[0]
The best way to change style IMO is to set a class. You do this by setting (or expanding) the .className
property of the resulting element.
Otherwise you can set the individual styles using the .style
property.
update
As @Randy Hall pointed out, perhaps you wanted to first li
of all ul
elements. In that case, I would use querySelectorAll
like this:
document.querySelectorAll("ul > li:first-child")
Then iterate the result to set the style.
To use getElementsByTagName
, you could do this:
var uls = document.getElementsByTagName("ul");
var lis = [].map.call(uls, function(ul) {
return ul.children[0];
});
You'll need an Array.prototype.map()
shim for IE8 and lower.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…