What is the difference between jQuery.map() and jQuery.each() Functions in jQuery?



jQuery map function

The map method translates a set of elements in the jQuery object into another set of values in a jQuery array which may, or may not contain elements.

Example

You can try to run the following code to learn how to work with jQuery.map() method:

Live Demo

<html>

   <head>
      <title>jQuery Map Method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function(){
           
            var mappedItems = $("li").map(function (index) {
               var replacement = $("<li>").text($(this).text()).get(0);
               
               if (index == 0) {
                  // make the first item all caps
                  $(replacement).text($(replacement).text().toUpperCase());
               } else if (index == 1 || index == 3) {
                  // delete the second and fourth items
                  replacement = null;
               } else if (index == 2) {
                  // make two of the third item and add some text
                  replacement = [replacement,$("<li>").get(0)];
                  $(replacement[0]).append("<b> - A</b>");
                  $(replacement[1]).append("Extra <b> - B</b>");
               }

               // replacement will be an dom element, null,
               // or an array of dom elements
               return replacement;
            });
               
            $("#results").append(mappedItems);
         });
      </script>
       
      <style>
         body {
            font-size:16px;
         }
         ul {
            float:left;
            margin:0 30px;
            color:blue;
         }
         #results {
            color:red;
         }
      </style>
   </head>
   
   <body>

      <ul>
         <li>First</li>
         <li>Second</li>
         <li>Third</li>
         <li>Fourth</li>
         <li>Fifth</li>
      </ul>
       
      <ul id = "results">
      </ul>
       
   </body>
   
</html>

jQuery each function

The each() method is a function to run for each matching element.

Example

You can try to run the following code to learn how to work with each function in jQuery:

Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $("button").click(function(){
      $("li").each(function(){
         alert($(this).text())
      });
   });
});
</script>
</head>
<body>

<button>Value</button>

<ol>
  <li>India</li>
  <li>US</li>
  <li>UK</li>
</ol>

</body>
</html>

Advertisements