user962206
user962206

Reputation: 16117

Selecting custom 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>

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/

Upvotes: 12

Views: 33973

Answers (5)

Adriano Ernesto
Adriano Ernesto

Reputation: 11

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

Takes the attribute value and stores the variable value

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

After this warning the variable value

alert (value);

Upvotes: 0

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

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/

Upvotes: 19

Robin Drexler
Robin Drexler

Reputation: 4457

$(this).attr('data-value') 

should also work.

Upvotes: 6

Clyde Lobo
Clyde Lobo

Reputation: 9174

$(this) refers to the current li element hence you get the element alerted.

You can try what the others have suggested i.e $(this).data("value")

Upvotes: 1

S P
S P

Reputation: 4643

You can use in your case:

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

in order to retrieve the value.

Upvotes: 1

Related Questions