Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

jQuery map method

Suggested Videos
Part 24 - jQuery insert element before and after
Part 25 - jquery add or remove class
Part 26 - Difference between $.each and .each



In this video we will discuss jQuery map method



Just like jquery each() method, map() method is also used to iterate over matched elements. 

However, there are some differences between map() and each() methods which we will discuss in our next video.

In general, if you want to create an array or concatenated string based on all matched elements in a jQuery selector, it is better to use map() over each() method.

Consider the following HTML
<ul>
    <li>US</li>
    <li>India</li>
    <li>UK</li>
    <li>Canada</li>
    <li>Australia</li>
</ul>

To create an array of list item text values, we could use either map() or each() methods. 

Using each() method
$(document).ready(function () {
    var result = [];

    $('li').each(function (index, element) {
        result.push($(element).text());
    });

    alert(result);
});

Using map() method
$(document).ready(function () {
    alert($('li').map(function (index, element) {
        return $(element).text();
    }).get());
});

To create a pipe delimited string of all list item text values, we could use either map() or each() methods. The output should be as shown below.
US|India|UK|Canada|Australia

Using each() method
$(document).ready(function () {
    var result = '';

    $('li').each(function (index, element) {
        result += $(element).text() + "|";
    });
    result = result.substr(0, result.length - 1);

    alert(result);
});

Using map() method
$(document).ready(function () {
    alert($('li').map(function (index, element) {
        return $(element).text();
    }).get().join('|'));
});

In our next video, we will discuss the differences between map and each methods and when to use one over the other.

jQuery tutorial for beginners

No comments:

Post a Comment

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.