jQuery - .map()

In jQuery, .map() is used to transform a collection of elements and return a new jQuery object (or array) based on the function you provide. It’s similar to the array .map() method but works on jQuery collections.


1. Syntax

$(selector).map(function(index, element) {
    // Return a transformed value
});
  • index → the position of the element in the jQuery collection

  • element → the actual DOM element (not a jQuery object)

  • Return value → Can be a single value or array of values. Use $(...) to wrap elements if you want a jQuery object.


2. Example: Transform elements into an array of text

<ul>
  <li>Apple</li>
  <li>Banana</li>
  <li>Cherry</li>
</ul>
var fruits = $('li').map(function(index, elem) {
    return $(elem).text(); // Get the text of each li
}).get(); // .get() converts jQuery object into a plain array

console.log(fruits); 
// Output: ["Apple", "Banana", "Cherry"]
  • Without .get(), .map() returns a jQuery object, not a plain array.

  • .get() converts it into a standard JavaScript array.


3. Example: Transform elements into new elements

var newItems = $('li').map(function(index, elem) {
    return $('<p>').text('Fruit: ' + $(elem).text());
});

$('body').append(newItems); 
// Adds <p>Fruit: Apple</p>, <p>Fruit: Banana</p>, etc.
  • Here, each <li> is transformed into a new <p> element.

  • .map() allows collection transformation without manually looping.


4. Key Notes

  • .map() iterates over a jQuery collection.

  • The return value can be:

    • DOM elements → wrapped into a new jQuery object

    • Strings, numbers → becomes an array with .get()

  • It flattens arrays automatically if you return an array inside .map().