Q:

How to Loop Through Elements with the Same Class in jQuery Topic: JavaScript / jQuery

0

How to Loop Through Elements with the Same Class in jQuery Topic: JavaScript / jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the jQuery each() Method

You can simply use the jQuery each() method to loop through elements with the same class and perform some action based on the specific condition.

The jQuery code in the following example will loop through each DIV elements and highlight the background of only those elements which are empty. Let's try it out:

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Loop Through Elements with the Same Class</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<style>
    .box{
        min-height: 20px;
        padding: 15px;        
        margin-bottom: 10px;
        border: 1px solid black;
    }
</style>
<script>
$(document).ready(function(){
    // Loop through each div element with the class box
    $(".box").each(function(){
        // Test if the div element is empty
        if($(this).is(":empty")){
            $(this).css("background", "yellow");
        }
    });
});
</script>
</head>
<body>
    <div class="box">A Div box</div>
    <div class="box"></div>
    <div class="box extraclass">Another Div box</div>    
    <div class="box">One more Div box</div>
    <div class="box extraclass"></div>
</body>
</html>

In the above example $(this) represent the current DIV element in the loop. You can attach jQuery methods directly to $(this) to perform manipulations.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Allow Only Numeric Value in HTML Text Input... >>
<< How to Change the Text of a Button using jQuery...