13

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

4 Answers 4

34

Something like

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

Working demo

Sign up to request clarification or add additional context in comments.

Comments

23

Something like this perhaps?

var ids = [];

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

3 Comments

Why are you creating a jQuery object ($(this).attr('id')) rather than simply the native this.id?
@David Thomas - force of habit more than anything else, probably, but I'll amend the answer.
@DavidThomas: this.id only works for the id attribute because this is a DOM note. For the general case, e.g. href, you need either this.getAttribute('href') or $(this).attr('href').
2

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>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.