How to use the jQuery .each() method for efficient element iteration?

Here is a simple example where I’m using jQuery .each() to highlight each list item by iterating over them :

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Each Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <link rel="stylesheet" href="styles.css">
</head>
<body>

  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
  </ul>

  <script src="script.js"></script>

</body>
</html>
CSS
/* Add your styles here if needed */
.highlight {
  background-color: yellow;
}
JavaScript
$(document).ready(function() {
  // Select all li elements within the ul
  var listItems = $('ul li');

  // Using $.each() to iterate over the elements
  $.each(listItems, function(index, element) {
    // Access the current element using $(element)
    console.log('Index:', index, 'Text:', $(element).text());
    
    // You can perform any operations with the current element here
    // For example, adding a class to each li element
    $(element).addClass('highlight');
  });
});

Leave a Reply

Your email address will not be published. Required fields are marked *