The map method

The map method calls a given function on each element of a set. It is especially useful for getting or setting the values ​​of a collection of elements. The map method returns a newly formed set of different elements and objects, unlike the each method, which returns the original set of elements.

Syntax

The elements themselves are available in the function, in the variable this, and their ordinal numbers in the set — in the variable index:

javascript$(selector).map(function(index, element));

Example

Let's print a list of id element names separated by commas. We'll also use the get and join methods:

html<p id="aaa">text1</p>
<p id="bbb">text2</p>
<p id="ccc">text3</p>
javascriptconsole.log(
  $('p').map(
    function() {
      return this.id; 
    }
  ).get().join()
);

See also

  • method filter,
    which filters elements by a specific selector
  • method each,
    which calls a given function for each element of a set