Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an array of attribute value from elements in a jQuery object

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?

like image 951
garyM Avatar asked Mar 10 '12 16:03

garyM


Video Answer


3 Answers

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"
like image 171
Tomalak Avatar answered Sep 20 '22 17:09

Tomalak


Simple solution (ES6)

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

Online demo (jsFiddle)

like image 24
Ali Soltani Avatar answered Sep 18 '22 17:09

Ali Soltani


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.

like image 39
gilly3 Avatar answered Sep 22 '22 17:09

gilly3