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");
}).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"
Simple solution (ES6)
Array.from(document.getElementsByClassName('tab_item')).map(item => item.getAttribute('foo'));
Online demo (jsFiddle)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With