19

I use a custom attribute in elements with my own class. I'm trying to return the value of custom attribute for all elements of the class.

I used jQuery to find the elements by class, and jQuery places the object in an array.

var tabs = $('li.tab_item');

Now that I'd have the objects in an array, I would like to return the value for the custom attribute for all the array's members.

How can this be done?

0

3 Answers 3

34
var tab_attribs = $('li.tab_item').map(function () {
  return $(this).attr("custom_attribute");
}).toArray();

This will give you an array of the custom attribute values. Of course, you can do this more traditionally:

var tab_attribs = [];
$('li.tab_item').each(function () {
  tab_attribs.push( $(this).attr("custom_attribute") );
});

Anyway, you should probably make use of the data-* attributes that HTML5 provides:

<li class="tab_item" data-foo="some custom data">

and (see jQuery data()):

$('li.tab_item').data("foo"); // -> "some custom data"
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks... both on the top worked $('li.tab_item').data("foo"); // only returns one entry
Ahh... I thought it worked like $('li.tab_item') .. returning an array. In the jQuery doc, it mentions that fact for ".attr()". Again thanks ...
@garyM Everything in jQuery that returns a value breaks the chain. That's true for getting .text(), .html(), .attr('xyz') and the like. However, if a method is not returning an immediate value, like setting .attr('xyz', 'new value'), it returns the elements that were previously matched, i.e. an array.
just add, tab_attribs.toArray()
@Hatim is right, without toArray() you will get a jquery collection instead of an array!
|
7

Use .map():

 $("li.tab_item").map(function (){
    return this.getAttribute("myAttribute");
 });

That gives you an Array of values wrapped in a jQuery object. If you want to get the Array, call .get(), ie .map(...).get().

By the way, you can also select the elements by attribute instead of class:

$("[myAttribute]")

This will return all elements on the page that have a myAttribute attribute.

Comments

6

Simple solution (ES6)

Array.from(document.getElementsByClassName('tab_item')).map(item => item.getAttribute('foo'));

Online demo (jsFiddle)

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.