Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Get IDs of Multiple Elements with Less Code using jQuery

3.35/5 (8 votes)
4 Sep 2015CPOL 14.6K  
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:

HTML
<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

JavaScript
// 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 <a href="http://api.jquery.com/jquery.map/" target="_blank">.map()</a>:

JavaScript
// 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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)