Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all the data attributes with same class name jquery

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.

like image 342
Prabhakaran Avatar asked Jan 17 '26 14:01

Prabhakaran


2 Answers

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:

  1. 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>
    
  2. 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... */
    });
    
like image 72
Ashish Kumar Avatar answered Jan 20 '26 02:01

Ashish Kumar


try this

 $('.sel').each(function(){
   console.log($(this).attr('data-tes'));
})
like image 34
Karthick Kumar Avatar answered Jan 20 '26 03:01

Karthick Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!