Get attribute value of each element from jQuery set to array

How can I get all the attributes (e.g. href ) of all elements matching the jQuery selector?

+7
jquery jquery-selectors get attributes
source share
4 answers

Is something like this possible?

 var ids = []; $('.myClass').each(function () { ids.push($(this).attr('id')); // ids.push(this.id) would work as well. }); 
+18
source share

Something like

 var idArray = $(".someClass").map(function(){ return this.id }).get().join(','); 

Working demo

+26
source share

A simpler solution with Underscore.js

For example: Get the text of all links who have someClass

 _.pluck($('.someClass').find('a'), 'text'); 

Working violin

0
source share

Single-line with ES6 arrow functions using jQuery .map () :

 const ids = $('a.someClass').map((i, el) => el.getAttribute('href')).get(); console.log(ids); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href="test1" class="someClass">t1</a> <a href="test2" class="someClass">t2</a> <a href="test3" class="someClass">t3</a> 
0
source share

All Articles