Sometimes, we want to get data attribute value of all elements with jQuery.
In this article, we’ll look at how to get data attribute value of all elements with jQuery.
How to get data attribute value of all elements with jQuery?
To get data attribute value of all elements with jQuery, we can call the each
method on the select element list object.
Then we call data
on each element to get the data attribute value.
For instance, we write:
<ul>
<li class="myClass" data-option-id="2"></li>
<li class="myClass" data-option-id="15"></li>
<li class="myClass" data-option-id="27"></li>
</ul>
to add li elements in a ul element.
Then we write:
$('.myClass').each(function() {
console.log($(this).data('option-id'));
});
to select all elements with class myClass
.
Then we call each
with a callback to get all the data-option-id attribute values.
We get the value with the data
method with 'option-id'
as the argument.
As a result, we see 2, 15, and 27 are logged.
Conclusion
To get data attribute value of all elements with jQuery, we can call the each
method on the select element list object.
Then we call data
on each element to get the data attribute value.