This may have been asked, but scrolling through about 40+ search results reveals only the jQuery solution. Let\'s say I want to get the first item in an unordered list and a
Using the basic DOM operations:
var ul = document.getElementById('id of ul');
var child = ul.childNodes[0];
Also consider sizzle, depending on your needs. Smaller than jQuery, but handles all your selector normalization.
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/
Since the only valid child of <ul>
is <li>
, you can do this:
var firstLI = document.getElementsByTagName('ul')[0].children[0];
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.