Get first <li> WITHOUT jquery
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.
document
.getElementsByTagName("ul")[0]
.getElementsByTagName("li")[0]
.style.color = "blue";
If you need to change style only, use CSS :first-child
ul > li:first-child {
color: blue;
}
works even in IE7 http://caniuse.com/#feat=css-sel2
http://jsfiddle.net/Tymek/trxe3/