65.9K
CodeProject is changing. Read more.
Home

Get IDs of Multiple Elements with Less Code using jQuery

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.35/5 (8 votes)

Sep 4, 2015

CPOL
viewsIcon

14616

How to get the IDs of multiple elements with less code using the power of jQuery

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

// Create an empty array to store the ids
var tempArray = [];

// Loop through all the div tags
$('div').each(function () {

    // Getting the id of each div
    var id = $(this).attr('id');

    // Add to the array
    tempArray.push(id);
});

// Show the ids in a span to the users
$('#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 .map():

// Create an empty array to store the ids and use map
var tempArray = $('div').map(function () {
	return this.id;
}).get();

// Show the ids in a span to the users
$('#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