Add a class to every list item with jQuery

Written by on August 23, 2012 in jQuery - No comments
jquery-list-item

What if have a list created dynamically and you need to target each list with CSS? Since you can’t manually add a class to each list item you should use jQuery to automatically add a class to each list item.

Say your list looks like this:

<ul id="awesome-list">
 <li>First Item</li>
 <li>Second Item</li>
 <li>Third Item</li>
 <li>Fourth Item</li>
 <li>Fifth Item</li>
</ul>

Use the following jQuery:

$("#awesome-list > li").addClass(function(i){return "item" + (i + 1);});

The result will be:

<ul id="awesome-list">
 <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>

Now you have a way to target each list item with CSS.

source

Sponsors

About the Author

Mike Ilsley "ilz" is a Boston based website designer, front-end developer, WordPress addict, owner of Beantown Design, and exclusive ThemeForest author. Follow him on Twitter and Facebook, and don't forget to subscribe to the WebDesign&Such email RSS feed. Also, check out his latest project, jQueryMobileShowcase.com.