Introduction
This code snippet is basically used to get the IDs of multiple elements with less code using the power of jQuery.
Background
Let's say we have an HTML markup like this:
<div id="divA">DIV A</div>
<div id="divB">DIV B</div>
<div id="divC">DIV C</div>
Now, we want to get the ids of all the div
tags. Basically, I have seen many using the below version for this purpose.
JS
var tempArray = [];
$('div').each(function () {
var id = $(this).attr('id');
tempArray.push(id);
});
$('#result').html(tempArray.join('<br/>'));
Demo here: FIDDLE DEMO #1
Using the Code
Now I will show how the same task can be done with less code using jQuery <a href="http://api.jquery.com/jquery.map/" target="_blank">.map()</a>
:
var tempArray = $('div').map(function () {
return this.id;
}).get();
$('#result').html(tempArray.join('<br/>'));
Demo here: FIDDLE DEMO #2
Points of Interest
For people who might be wondering why the .get()
method is used here after using .map()
, as the return value of map method is a jQuery object, which contains an array, it's very common to call .get()
on the result to work with a basic array.
History
- Added on 4th September, 2015