How to get data attribute value of all elements using jquery without $.each?
<li class="myclass" data-optionid="2"></li>
<li class="myclass" data-optionid="15"></li>
<li class="myclass" data-optionid="27"></li>
The result should be: 2, 15, 17
I tried $('.myclass').data('optionid')
but the result was 2
Thanks in advance.
Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.
Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.
You can use the attribute selector: $('[data-my-key]').
ready(function() { $('#list li'). click(function() { alert($(this). attr("id")); alert($(this). text()); }); });
$('.myclass')
will select all the elements having the class myclass
, but when used .data()
on it will return the data-attribute value of the first element in the matched set, thus returning 2
.
As there are multiple elements having the data-attribute, you'll need to iterate over them using $.each
$('.myclass').each(function() { console.log($(this).data('optionid')); });
$('.myclass').each(function() { console.log($(this).data('optionid')); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <li class="myclass" data-optionid="2"></li> <li class="myclass" data-optionid="15"></li> <li class="myclass" data-optionid="27"></li>
If you want to get the result as array, use $.map
and $.get
var data = $('.myclass').map(function() { return $(this).data('optionid'); }).get();
var data = $('.myclass').map(function() { return $(this).data('optionid'); }).get(); console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <li class="myclass" data-optionid="2"></li> <li class="myclass" data-optionid="15"></li> <li class="myclass" data-optionid="27"></li>
Please try this
$(".myclass").each(function(){ alert($(this).attr("data-optionid")); });
I'm not sure if you noticed the small typo but first close the opening <li>
tags.
<li class="myclass" data-optionid="2"></li>
<li class="myclass" data-optionid="15"></li>
<li class="myclass" data-optionid="27"></li>
The with the jQuery code you don't have to do a $.each can just because jQuery does that in the initial element selector. So if you do a .prop on the selector to get the data-optionid then you will get the value.
$(".myclass").attr("data-optionid");
On of the flexible thins about HTML is that you can create your own attributes to use in other parts of our code. If the browser doesn't recognize it then it gets ignored.
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