How to get the first X elements?
I have a list with a bunch of elements:
<ul>
<li>text</li>
<li>text</li>
<li>text</li>
&l开发者_如何学Got;li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
How can I target the first five li
elements and add a class to them?
Use the :lt
selector:
$("ul > li:lt(5)").addClass("foo");
Apart from :lt()
selector, you can also use slice()
function.
$('li').slice(0, 5).addClass('someClass');
$('ul li:lt(5)')
This selects all <li>
s of <ul>
whose index is less than 5 (i.e., 0-4, or the first five)
for the first five you will want to use
$('ul li:lt(5)').addClass('first-five');
If you're using $.each method, and you want to use a limit condition into it, i would suggest the following:
var $elems = $('ul li');
$.each($elems, function(i){
var $this = $(this);
if (i < n) {
$this.addClass('someClass');
} else {
$this.addClass('anotherClass');
}
});
精彩评论