Helping you solve those tough coding problems!

Manipulating an array of DOM elements with jQuery $.map() Manipulating an array of DOM elements with jQuery $.map()

Published on Mar 12, 2019 by Jamie Munro

jQuery's $.map() function is a pretty neat function. It accepts an array as a parameter and then will iterate through each item in the array allowing you to further manipulate and build a new array with that data. This article will explore how to use it while providing a useful example.




Html setup for $.map



In this example, I am going to convert an unordered list of categories into a comma delimited list adding the ", and" for the last element. To begin, you will need a list of categories, for this example, I will use an example main menu:


<ul id="top-nav">

<li><a href="https://www.endyourif.com/">Home</a></li>
<li><a href="https://www.endyourif.com/category/php/" title="View all posts filed under PHP">PHP</a></li>
<li><a href="https://www.endyourif.com/category/javascript/" title="View all posts filed under Javascript">Javascript</a></li>
<li><a href="https://www.endyourif.com/category/asp-net/" title="View all posts filed under ASP.NET">ASP.NET</a></li>
<li><a href="https://www.endyourif.com/category/database/" title="View all posts filed under Database">Database</a></li>
<li><a href="https://www.endyourif.com/category/html5/" title="View all posts filed under HTML5">HTML5</a></li>
<li><a href="https://www.endyourif.com/category/css/" title="View all posts filed under CSS">CSS</a></li>
</ul>


Next up is the jQuery that will iterator through each list item above and convert it into a new array.


<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script>
var total = 0;
$(document).ready(function(){
total = $("li").size();
var items = $.map($("li"), function(elem, count){
if (count + 1 < total) {
return $(elem).text();
} else {
return 'and ' + $(elem).text();
}
});
$("body").append("Here are the categories: " + items.join(", "));
});
</script>


Review the $.map() Javascript

In the above code, I am "mapping" the li items: $.map($("li") and passing the data to a function. By returning the text value of the list item the category is being appended to the new array items. If I didn't want to return a specific value, returning null would not add that value to the new array. Finally, when the last item is being added, the word "and" is prepended before the category name.

Once the array has been created, the contents are appended to the body by using the join function to return a comma delimited list from the array elements.

Converting one array into another while performing manipulation on each item is accomplished easily by using the jQuery $.map() function.

Tags: jquery | jQuery

My Books