Loop through list items of an unordered list using jQuery.

Suppose you have an unordered list with so many list items and you want to call a JavaScript function for each list item, the days are gone when you would put an onlick() attribute for each list item, we can now perform a loop on list items without even touching them!

Here is our unordered list with list items:


Now let’s loop through the list and show an alert with the id of each item. Below is the Javascript code to achieve our goal, please note you must include jquery library in your page’s <head> tag for the script to work:

$('#menu li').each(function() {

   alert(this.id);

});

Leave a Reply