Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use map function in jquery?

I am trying to add 10 number(digit) in each element using map function on button click.I tried like this

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <style>


    </style>
  </head>

  <body>

    <button class="add">ADD</button>
    <ul class="item">
      <li class="abc">123</li>
      <li class="pp">12</li>
      <li class="abc">78</li>
      <li class="ac">13</li>
    </ul>
    <script>
    $(function () {

        $('.add').click(function () {
            var $items = $('.item li');
            var $newItem =$items.map(function (i,item) {
                console.log($(item).text())
                return $(item).text() +10;
            });
            console.log($newItem)
        });

    });
    </script>
  </body>

</html>

Expected output

133
22
88
23
like image 546
user5711656 Avatar asked Mar 16 '26 08:03

user5711656


1 Answers

All you need is actually to chain .get() after calling the .map() function, which will return you the array that you have constructed, e.g.:

var $newItem = $items.map(...).get();

The reason why .get() is needed is because .map() generates an array-like object. Since you have started off with a collection of jQuery objects ($newItem), it will return a DOM node list. In order to get the array you intended, you have to call .get() to return a true array (not a DOM node list). A better explanation of why this is needed is available here: map() get() confusion

On a side note, $(item).text() will not be automatically casted into a Number. This means that if the value of the text if 123, it is actually seen as a string. The + operator will concatenate but not perform addition, i.e. $(item).text() + 10 will give you 12310 instead of 133. In order to cast it to a number, simply prepend a unary + operator in front of the variable: +$(item).text() + 10.

Here is a proof-of-concept example of your scenario, with the two modifications mentioned above applied:

$(function() {

  $('.add').click(function() {
    var $items = $('.item li');
    var $newItem = $items.map(function(i, item) {
      console.log($(item).text())
      return +$(item).text() + 10;
    }).get();
    console.log($newItem)
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">ADD</button>
<ul class="item">
  <li class="abc">123</li>
  <li class="pp">12</li>
  <li class="abc">78</li>
  <li class="ac">13</li>
</ul>
like image 132
Terry Avatar answered Mar 18 '26 21:03

Terry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!