How to Loop Through Elements with the Same Class in jQuery
Topic: JavaScript / jQueryPrev|Next
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:
Example
Try this code »<!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.
Related FAQ
Here are some more FAQ related to this topic: