How to get all the data attributes with same class name jquery
javascript, jquery
Solution
Two things to look at:
The first is that within your `each` iterator function, you're doing `$('.sel').data('tes')`, which will only ever look at the first element matching `.tes` in the document. If you want to look at the attribute for the current element being iterated in the loop, use `$(this).data('tes')` instead:
$('.sel').each(function(){
console.log($(this).data('tes'));
// Here ----^^^^^^^
});
(Or if you just need to get the value and you aren't using the various other features of `data`, just use `attr`: `$(this).attr('data-tes')`.)
The second thing is to make sure these elements exist when that code runs. Two ways to do that:
Make sure the `script` tag containing the code is below the tags defining the elements in the HTML (which is recommended):
...content...
<script>/* ...your code here... */</script>
</body>
</html>
Or alternately if you don't control where the `script` tags go, use jQuery's `ready` callback, which will call a function you provide on "DOM ready" (when the elements are there):
$(document).ready(function(){
/* ...your code here... */
});
Problem
Consider the following `data` attributes ``` <li data-tes='rwer-234;sdf-23;gfd-345' class='sel'>Some text</li> <li data-tes='zxc-23;vcx-12' class='sel'>Some text1</li> ``` I tried ``` $('.sel').each(function(){ console.log( $('.sel').data('tes') ); }) ``` Getting output as `undefined.`