each Function

How to use each function in jquery?

Each function is used in jquery when we want to display a list multiple items.

The each  function  is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

Ex:

<ul>

  <li>Item 1</li>

  <li>Item 2</li>

</ul>

$( “li” ).each(function( index ) {

  console.log( index + “: ” + $( this ).text() );

});

Op:

0: Item 1
1: Item 2

Using the each function we are able to display a list with index value.