4

I'm parsing through a web page and I need to return every single attribute VALUE (note: not element) of any element tagged with a specific attribute.

A page example is below. The structure and ordering will vary from page to page, but I'm focused on only returning the value of each instance of attrX (red, blue, green, purple, etc)

<div attrX="red"></div>
<div attrX="blue"></div>
<span attrX="green></span>
<div>
  <p attrX="purple"></p>
</div>

how can I use jQuery to return an array of the value for each instance on the page of the attribute 'attrX' in the following format (order doesn't actually matter)?

[0]->"red"
[1]->"blue"
[2]->"green"
[3]->"purple"

Thanks!

2 Answers 2

6

Try the following:

var values = [];
$('[attrX]').each(function() {
  var value = $(this).attr('attrX');
  values.push(value);
});

See here for jsFiddle.

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

2 Comments

oh I didn't realize you can select an element based on its attribute?
Yep, see api.jquery.com/category/selectors/attribute-selectors for all the variants of the selector.
1

Try this:

var values = $('[attrX]').map(function() {
    return $(this).attr('attrX');
}).get();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.