tadam logo
Did you find an error in the text?
Select this with mouse and press
Ctrl + Enter
Xhtml.co.il Check Spelling
Orphus system

.map( callback(index, domElement) )

Returns: jQuery

Description: Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

.map( callback(index, domElement) )

version added: 1.2
callback(index, domElement)
A function object that will be invoked for each element in the current set.

As the return value is a jQuery-wrapped array, it's very common to get() the returned object to work with a basic array.

The .map() method is particularly useful for getting or setting the value of a collection of elements. Consider a form with a set of checkboxes in it:

<form method="post" action="">
  <fieldset>
    <div>
      <label for="two">2</label>
      <input type="checkbox" value="2" id="two" name="number[]">

    </div>
    <div>
      <label for="four">4</label>
      <input type="checkbox" value="4" id="four" name="number[]">
    </div>

    <div>
      <label for="six">6</label>
      <input type="checkbox" value="6" id="six" name="number[]">
    </div>
    <div>

      <label for="eight">8</label>
      <input type="checkbox" value="8" id="eight" name="number[]">
    </div>
  </fieldset>
</form>
We can get a comma-separated list of checkbox IDs:
$(':checkbox').map(function() {
  return this.id;
}).get().join(',');

The result of this call is the string, "two,four,six,eight".

Within the callback function, this refers to the current DOM element for each iteration. The function can return an individual data item or an array of data items to be inserted into the resulting set. If an array is returned, the elements inside the array are inserted into the set. If the function returns null or undefined, no element will be inserted.

Examples

Example 1

Build a list of all the values within a form.
    $("p").append( $("input").map(function(){
      return $(this).val();
    }).get().join(", ") );

The output of the code above will be:

Example 1 - Full source:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script type="text/javascript" language="javascript">

  $(document).ready(function(){
    
    $("p").append( $("input").map(function(){
      return $(this).val();
    }).get().join(", ") );

  });
  </script>

  <style>
  p { color:red; }
  </style>

</head>
<body>
  <p><b>Values: </b></p>

  <form>
    <input type="text" name="name" value="John"/>

    <input type="text" name="password" value="password"/>
    <input type="text" name="url" value="http://ejohn.org/"/>
  </form>
</body>

</html>

Example 2

A contrived example to show some functionality.
    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);
The output of the code above will be:

Example 2 - Full source:

A contrived example to show some functionality.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script type="text/javascript" language="javascript">

  $(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>

Example 3

Equalize the heights of the divs.
$.fn.equalizeHeights = function(){
  return this.height( Math.max.apply(this, $(this).map(function(i,e){ return $(e).height() }).get() ) )
}
$('input').click(function(){
  $('div').equalizeHeights();
});
The output of the code above will be:

Example 3 - Full source

Equalize the heights of the divs.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <style>
div { width: 40px; float:left; }
input { clear:left}
  </style>

<script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script type="text/javascript" language="javascript">
  $(document).ready(function(){
     $.fn.equalizeHeights = function(){
  return this.height( Math.max.apply(this, $(this).map(function(i,e){ return $(e).height() }).get() ) )
}
$('input').click(function(){
  $('div').equalizeHeights();
});
  });
  </script>

</head>
<body>

<input type="button" value="equalize div heights">

<div style="background:red; height: 40px; "></div>
<div style="background:green; height: 70px;"></div>
<div style="background:blue; height: 50px; "></div>

</body>
</html>
Was this information helpful?
   

Comments