• here
  • Selecting user data attributes in jQuery

    I have a list here

    <ul id="demo2" data-name="demo2"> <li data-value="here">here</li> <li data-value="are">are</li> <li data-value="some...">some</li> <!-- notice that this tag is setting a different value :) --> <li data-value="initial">initial</li> <li data-value="tags">tags</li> </ul> 

    If each li element has its own data attribute. In jQuery, how to get all the values ​​of each li element that has a data value attribute? I want to get their value.

    but this code does not work

      $('#view-tags').click(function(){ $('li[data-value]').each(function(){ alert($(this).data("value")); }) }); 

    All code in jsfiddle: http://jsfiddle.net/Zn3JA/

    +7
    source share
    5 answers

    You are pretty close. You can use the jQuery .data() method to read attributes starting with data- . So, in your case .data("value") , since your attribute is data-value="some" .

    This should do it:

     $('li[data-value]').each(function(){ alert($(this).data("value")); }); 

    Here is the working fiddle: http://jsfiddle.net/nuphP/

    +7
    source
     $(this).attr('data-value') 

    should also work.

    +3
    source

    You can use in your case:

      jQuery(this).data("value"); 

    to get the value.

    +1
    source

    $(this) refers to the current li element, so you get an element warning.

    You may try others suggested ie $(this).data("value")

    +1
    source
      $('#view-tags').click(function(){ $('li[data-value]').each(function(){ var value = $(this).attr('data-value'); alert(value); }) }); // this work normally 

    Accepts an attribute value and stores the value of a variable

     var value = $ (this) .attr ('date value'); 

    After this warning, the value of the variable

     alert (value); 
    0
    source

    All Articles