jQuery Map()

The jQuery map() method applies a function to each element in a jQuery collection or array and returns a new jQuery object containing the results. This method is useful for transforming collections or extracting data from elements.

Key Topics

Basic Usage of map()

The map() method transforms elements in a collection based on the function provided.

var texts = $("li").map(function(index, element) {
    return $(element).text();
}).get();
console.log(texts);

Explanation: This code extracts the text content of all <li> elements and stores it in an array.

Processing Data with map()

You can use map() to process or manipulate data from elements and return transformed values.

var modified = $("li").map(function(index, element) {
    return "Item " + index + ": " + $(element).text();
}).get();
console.log(modified);

Explanation: This code prefixes the index to each <li> text and stores the transformed strings in an array.

Example: Using map()


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Map Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <ul>
        <li>Apple</li>
        <li>Banana</li>
        <li>Cherry</li>
    </ul>
    <button id="transformButton">Transform List</button>
    <div id="output"></div>

    <script>
        $(document).ready(function() {
            $("#transformButton").click(function() {
                var transformed = $("li").map(function(index, element) {
                    return "Item " + (index + 1) + ": " + $(element).text();
                }).get();

                $("#output").html(transformed.join("<br>"));
            });
        });
    </script>
</body>
</html>
                    

Explanation: This example uses map() to extract and transform the text of list items, appending the results to a div when a button is clicked.

Key Takeaways

  • Data Extraction: Use map() to extract data from a collection of elements.
  • Transformation: Modify or transform data using the provided function.
  • Array Conversion: Use get() to convert the results into a standard JavaScript array.