How To Loop Through The Elements With Same Class In Jquery

For More Videos Visit Our YouTube Channel




Here we consider how to loop through form elements with same class in jQuery. Lets start with one example here. Suppose we have three div with same class divClass as shown below.

Loop Through Elements With Same Class In Jquery, Loop Through Elements With Same Class, Loop Through Elements With Same Class In JavaScript, Loop Through Same Class Elements, Loop Through Divs With Same Class, Loop Through links With Same Class, Loop Through Button With Same Class In Jquery, Loop Through, jQuery Each, For Each, Jquery, HTML

The style applied for these divs are given below. All of them are given with a background color as red.

.divClass {
         height: 200px;
         width: 300px;
         background: red;
}



For the third Div, we needs to give a background color as yellow.
So this can be achived in JQuery as follows. We have to loop through all divs with class divClass.

$(function () {
         $('.divClass').each(function (i, obj) {
                  if (i == 2) {
                           $(this).css('background', 'yellow');
                  }
         });
});



Here we have used jQuery each for iterating through divs with class divClass. If it is third Div, means i = 2, we have used $(this) for accessing that third Div. And then apply a background color as yellow for this Div. That's all by this way we can loop through the elements with same class in jQuery.