Friday, 20 August 2021

jQuery each method -iterate over elements using jQuery

Hi guys, in this post we will see how to use jQuery each method. jQuery each method is used to iterate over elements. jQuery each method provides the function to run for matched element. Let's see it practically. We have following unordered list of names of countries.

  • USA
  • India
  • Australia
  • Belgium
  • Bulgaria
Now, we will use jQuery each method to iterate over above list of elements and show names in alert.

jQuery each method

Please follow below steps:-

1)Open notepad.
2)Add html tags such as html,head,script,body tag.
3)Add jquery CDN link in head section as:-

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

4)Add unordered list of countries using <ul> tag.

<p>List of countries:-</p>
   <ul>
<li>USA</li>
<li>India</li>
<li>Australia</li>
<li>Belgium</li>
<li>Bulgaria</li>
   </ul>

5)  Add button control.

   <button Id="btnSubmit">Submit</button>
6) Add jquery code in script tag:-

In code first we have added document ready function. Then add button click event handler. So, on click on button control we will iterate over <li> elements using each() method. 

<script type="text/javascript">
$(document).ready(function(){
$('#btnSubmit').click(function(){
$('li').each(function(){
alert($(this).text());
});
});
});
</script>

Full Code for Demo:-

<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#btnSubmit').click(function(){
$('li').each(function(){
alert($(this).text());
});
});
});
</script>
</head>
<body>
   <p>List of countries:-</p>
   <ul>
<li>USA</li>
<li>India</li>
<li>Australia</li>
<li>Belgium</li>
<li>Bulgaria</li>
   </ul>
   <button Id="btnSubmit">Submit</button>
</body>
</html>

Screenshot of code:-

jQuery each method





No comments:

Post a Comment