Get the first <li> WITHOUT jQuery
It may have been asked, but scrolling around 40 search results only shows the jQuery solution. Let's say I want to get the first element in an unordered list and apply a new text color to it, and it is one. It 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: how can I achieve this without jQuery?
SOLUTION: I found this method to work in all browsers (with IE7 +) →
document .getElementsByTagName("ul")[0] .getElementsByTagName("li")[0] .style.color = "blue"; You can use querySelector (IE7 and below is 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 the IMO style is to set the class. You do this by setting (or extending) the .className property of the resulting element.
Otherwise, you can set individual styles using the .style property.
Update
As @Randy Hall noted, perhaps you need li all ul elements first. In this case, I would use querySelectorAll as follows:
document.querySelectorAll("ul > li:first-child") Then repeat the result to set the style.
To use getElementsByTagName , you can do this:
var uls = document.getElementsByTagName("ul"); var lis = [].map.call(uls, function(ul) { return ul.children[0]; }); You will need the Array.prototype.map() padding for IE8 and below.
If you only need to change the style, use CSS: first-child
ul > li:first-child { color: blue; } works even in IE7 http://caniuse.com/#feat=css-sel2