Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

javascript - 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";
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...