Question

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.

Was it helpful?

Solution

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.

.data(key)

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top