Reputation: 1
How can I add several classes to ul list? I don't want to add it to every li items but just some of them.
EDIT:
I want to add classes with jQuery. Like this:
<ul>
<li>something1</li>
<li>something2</li>
<li>something3</li>
<li>something4</li>
<li>something5</li>
</ul>
And now I want to add class every li after the second one (3rd, 4th and 5th li element). I know how to add class but how can i make it to repeat in each li. Thats my problem really.
Upvotes: 0
Views: 522
Reputation: 722
you can use .filter()
method to filter down your selection.
$('li').filter(':nth-child(n+3)').addClass('className');
Now, anything meets this criteria, will receive the class attribute. In your example, 3rd, 4th and 5th li will receive it.
Upvotes: 0
Reputation: 108500
There are several ways to access a specific index of elements.
The :eq()
selector can access a single index:
$('li:eq(1)')
http://api.jquery.com/eq-selector/
The .nextAll()
function returns all following siblings of each element in the set of matched elements:
$('li:eq(2)').nextAll();
http://api.jquery.com/nextAll/
The .prevAll()
works the same way but returns the previous siblings:
$('li:eq(2)').prevAll();
http://api.jquery.com/prevAll/
Upvotes: 1
Reputation: 5220
Your question isn't detailed enough, but in general you'll want to set classes on the specific li elements as needed.
For example:
<ul>
<li class="first winter thirty-one">January</li>
<li class="winter">February</li>
<li class="spring thirty-one">March</li>
<li class="spring">April</li>
<li class="spring thirty-one">May</li>
<li class="summer">June</li>
<li class="summer schools-out thirty-one">July</li>
<li class="summer schools-out thirty-one">August</li>
<li class="fall">September</li>
<li class="fall thirty-one">October</li>
<li class="fall">November</li>
<li class="last winter thirty-one">December</li>
</ul>
Upvotes: 1
Reputation: 28205
Well, to add 3 classes to every li
in a ul
, you'd do:
$("#myUl > li").addClass("class1 class2 class3");
Since you don't specify any criteria for the li
elements you want to get the additional classes, I'm forced to guess:
$("#myUl > li:even").addClass("class1 class2 class3");
That will add the three classes to every other li
(the even numbered elements in a zero-indexed array, to be more precise).
Good luck.
Upvotes: 1