Selecting custom data attributes in JQuery

user962206 picture user962206 · Aug 1, 2012 · Viewed 26.1k times · Source

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>

Where each li item has a custom data attribute. On JQuery how would get all of the values of each li element which has an attribute of data-value? I want to get their value.

but this code of mine doesn't seem to be working

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

The whole code on jsfiddle: http://jsfiddle.net/Zn3JA/

Answer

Christofer Eliasson picture Christofer Eliasson · Aug 1, 2012

You are pretty close. You can use jQuery's .data() method to read attributes that start 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 a working fiddle as well: http://jsfiddle.net/nuphP/