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):Or
querySelectorAll:Or
getElementsByTagName:The best way to change style IMO is to set a class. You do this by setting (or expanding) the
.classNameproperty of the resulting element.Otherwise you can set the individual styles using the
.styleproperty.update
As @Randy Hall pointed out, perhaps you wanted to first
liof allulelements. In that case, I would usequerySelectorAlllike this:Then iterate the result to set the style.
To use
getElementsByTagName, you could do this:You’ll need an
Array.prototype.map()shim for IE8 and lower.