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 apply a new text color to it, and it alone. This is simple with jQuery.
Markup ->
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
With jQuery ->
$("ul > li:first").css("color", "blue");
Question is, how do I achieve this without jQuery?
SOLUTION: I found this method to work across all browsers (inc IE7+) ->
document
.getElementsByTagName("ul")[0]
.getElementsByTagName("li")[0]
.style.color = "blue";
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With