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
user962206
source share5 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
Christofer eliasson
source share$(this) refers to the current li element, so you get an element warning.
You may try others suggested ie $(this).data("value")
+1
Clyde lobo
source share $('#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
Adriano ernesto
source share