jQuery each()

Introduction

Alert the text of each <li> element:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("li").each(function(){
      document.getElementById("demo").innerHTML += 
         $(this).text()+"<br/>";
    });/*  w  w  w  .  j  a v a2 s .  c  o m*/
  });
});
</script>
</head>
<body>

<p id="demo"></p>
<button>Alert the value of each list item</button>

<ul>
  <li>CSS</li>
  <li>HTML</li>
  <li>Javascript</li>
</ul>

</body>
</html>

The each() method sets a function to run for each matched element.

Returning false can be used to stop the loop early.

$(selector).each(function(index,element))
Parameter
Optional
Description
function(index,element)


Required.


A function to run for each matched element.
index - index position of the selector
element - current element



PreviousNext

Related