How to loop through elements with the same class using jQuery?

Learn, how can we traverse/loop through the elements which have same class using jQuery?
Submitted by Pratishtha Saxena, on September 07, 2022

Prerequisite: Adding jQuery to Your Web Pages

By using .each() loop of jQuery, the elements with the same class can be traversed. This loop helps to traverse the object and executes the function for every matched element. Therefore, it accepts a function as its parameter. The function here is taken in two arguments – index and element/value. The index is the integer value for the specific position of the selector. Whereas the element here is the value of the index positioned selector.

Syntax:

$(selector).each(function(index, element)); 

This is the basic functionality of a .each() loop. Since we need to filter the elements based on classes, hence, we need to specify the particular class's name in place of the selector. If the element traversed contains the specified class, then it will execute the function for that element. Otherwise, the execution will pass back to each() loop and move to the next element. This will go on until all the elements are not traversed respectively.

The below example demonstrates the whole functionality of this.

Example to demonstrate how to loop through elements with the same class

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Using jQuery Loop Through All The Elements Having Same Class</h2>
    <p>The elements having same class will turn into some other text.</p>
    <button type="button" id="button1">Click Here</button><br><br>
    <div class="week">- Monday is the First day of a week.</div>
    <div class="day">- Tuesday is the Second day of a week.</div>
    <div class="week">- Wednesday is the Third day of a week.</div>
    <div class="week">- Thursday is the Fourth day of a week.</div>
    <div class="day">- Friday is the Fifth day of a week.</div>
    <div class="day">- Saturday is the Sixth day of a week.</div>
    <div class="week">- Sunday is the Seventh day of a week.</div>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('#button1').on('click',function(){
            $('.week').each(function(){
                $(this).html('This is Class - week');
            })
    
            $('.day').each(function(){
                $(this).html('This is Class - day'); 
            })
        })
    });
  </script>
</html>

Output:

Example: Loop through elements with the same class





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.