Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 994
user962206 Avatar asked Aug 01 '12 12:08

user962206


People also ask

How can get custom data attribute value in jQuery?

To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).

How do I select an element with a data attribute?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.

Which jQuery selector is used to retrieve all elements with the attribute data attribute name?

You can use the attribute selector: $('[data-my-key]').


Video Answer


1 Answers

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

should also work.

like image 188
Robin Drexler Avatar answered Oct 22 '22 22:10

Robin Drexler