Reputation: 46318
I have code that looks like this:
<ul class="effects-list">
<li data-creative="1">Creative</li>
<li data-uplifted="3">Uplifted</li>
<li data-energetic="3">Energetic</li>
</ul>
Then Javascript to read the data attributes:
$(function() {
var effectData = $('.effects-list li');
var creative = effectData.data("creative");
var uplifted = effectData.data("uplifted");
var energetic = effectData.data("energetic");
console.log(creative);
console.log(uplifted);
console.log(energetic);
});
I end up with this in the console log:
1
undefined
undefined
Why is the script reading the information in the first li
element but not the second two?
What do I have wrong and how do I solve the problem?
Here is a fiddle with the code above. I am using jQuery 2.1.
Upvotes: 2
Views: 2368
Reputation: 388446
Since you are using the getter version of data()
, it will look only at the first element in the given set, which does not have the said data attributes.
Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
The solution is to use an attribute exists selector to target the correct element then fetch the data value. something like
var uplifted = effectData.filter('[data-uplifted]').data("uplifted");
Demo: Fiddle
Upvotes: 5