Menu Close

Jquery Each Function Example

Jquery each

Here, we will learn how to jQuery each function to run for each matched element.

Syntex: $(selector).each(function(index,element)) 

The each() method accepts the parameter function(index,element) which is the callback function that executes for each matched or selected element. Follow the below example to see how it works. 

In this example, each method will trigger the click event of the button and this will apply to each li element. So this method will iterate over each li element. The function of each method displays the texts of the corresponding li element using the alert box.

Example

Create the html file on your computer and place the below codes on this file.

<!DOCTYPE html>
<html>
<head>
    <title>Jquery Each Function Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h3>Click the below button</h3><br>
    <button>Click Here</button><br><br>
    <ul>
        <li>Team A</li>
        <li>Team B</li>
        <li>Team C</li>
        <li>Team D</li>
    </ul>
</body>
    <script>
        $(document).ready(function(){
        $("button").click(function(){
        $("li").each(function(){
            alert($(this).text())
                });
            });
        });
    </script>
</html> 

Create an external stylesheet and link it to the html file.

html, body{
  padding: 20px;
  margin: 20px;
}

button{
    background: #fdfdfd; 
}

button:hover{ 
    background: #cdcdcd;
}
 
Posted in HTML, jQuery, Web Technologies

You can also read...