tirenweb
tirenweb

Reputation: 31709

Get the attribute value of each element from a jQuery set, into an array

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

Upvotes: 13

Views: 16790

Answers (4)

Dan Dascalescu
Dan Dascalescu

Reputation: 152056

One-liner 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>

Upvotes: 2

pymen
pymen

Reputation: 6549

More simple solution with Underscore.js

For example: Get all links text who's parents have class someClass

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

Working fiddle

Upvotes: 0

rahul
rahul

Reputation: 187050

Something like

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

Working demo

Upvotes: 34

g.d.d.c
g.d.d.c

Reputation: 47988

Something like this perhaps?

var ids = [];

$('.myClass').each(function () {
  ids.push($(this).attr('id')); // ids.push(this.id) would work as well.
});

Upvotes: 23

Related Questions