powered by Slim Framework
enhanced by Nesbot.com

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

Published on Nov 14, 2011 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.




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 this websites main menu:


<ul id="top-nav">

<li><a href="http://www.webistrate.com/">Home</a></li>
<li><a href="http://www.webistrate.com/category/php/" title="View all posts filed under PHP">PHP</a></li>
<li><a href="http://www.webistrate.com/category/javascript/" title="View all posts filed under Javascript">Javascript</a></li>
<li><a href="http://www.webistrate.com/category/asp-net/" title="View all posts filed under ASP.NET">ASP.NET</a></li>
<li><a href="http://www.webistrate.com/category/database/" title="View all posts filed under Database">Database</a></li>
<li><a href="http://www.webistrate.com/category/html5/" title="View all posts filed under HTML5">HTML5</a></li>
<li><a href="http://www.webistrate.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>


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.

Summary


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

Tags: Javascript | jquery

<- HTML5: Displaying a Progress Bar  Home jQuery: Splitting an unordered list into multiple columns -> 
blog comments powered by Disqus