Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first <li> WITHOUT jquery

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";
like image 327
rgdigi Avatar asked Nov 01 '12 13:11

rgdigi


2 Answers

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.

like image 160
I Hate Lazy Avatar answered Oct 29 '22 11:10

I Hate Lazy


document
    .getElementsByTagName("ul")[0]
    .getElementsByTagName("li")[0]
    .style.color = "blue";
like image 36
Salman A Avatar answered Oct 29 '22 10:10

Salman A