简体   繁体   中英

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?

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

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"

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.

Simple solution (ES6)

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

Online demo (jsFiddle)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM