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

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

I used jQuery to search for elements by class, and jQuery puts the object in an array.

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

Now that I have the objects in the array, I would like to return a value for the custom attribute for all members of the array.

How can I do that?

+4
source share
2 answers
 var tab_attribs = $('li.tab_item').map(function () { return $(this).attr("custom_attribute"); }); 

This will give you an array of user 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") ); }); 

In any case, you should probably use 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" 
+8
source

Use .map() :

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

This gives you an array of values ​​wrapped in a jQuery object. If you want to get an array, call .get() , i.e. .map(...).get() .

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

 $("[myAttribute]") 

This will return all the elements on the page with the myAttribute attribute.

+6
source

Source: https://habr.com/ru/post/1400741/


All Articles