Add Class to Every List Item With jQuery

Adding class to list item with jQuery and HTML. Learn how to add class to every list item with jQuery.

Adding a new class to every list item is mess of work. Like (item1, item2, item3, …). You don’t want to touch original coding then another possible way is jQuery. Learn how to add class to every list item with jQuery.

Suppose you don’t want to touch the internal code on back-end then you can target your list item with  jQuery and add class to every list item.

Add Class to Every List Item With jQuery

List item in HTML without any class.

[html]
<ul id="list-without-class">
<li>First Item</li>
<li>Second Item</li>
<li>Third Item</li>
<li>Fourth Item</li>
<li>Fifth Item</li>
</ul>[/html]

use a single line jQuery to add class to every item in your list.

[javascript]$("#list-without-class > li").addClass(function(i){return "item" + (i + 1);});[/javascript]

The result will be item1, item2, item etc.

[html]<ul id="list-without-class">
<pre><li class="item1">First Item</li>
<li class="item2">Second Item</li>
<li class="item3">Third Item</li>
<li class="item4">Fourth Item</li>
<li class="item5">Fifth Item</li>
</ul>[/html]

Now you have a way to target each list item with CSS write your own style to make it eye catchy.

Video: Add Class to List using jQuery

Simple Video tutorial showing you the live result with two possibilities how you can customize this single line of code. We made a simple video do subscribe us on YouTube.

Leave a Reply

Your email address will not be published. Required fields are marked *