Search code examples
javascriptjqueryjquery-3

jQuery's data() function does not seem to be working right.


Previously I had been doing:

My HTML:

<span id="foo" data-foo-bar="42">The Answer</span>

My "jquery":

const fooElement = $('#foo');
const fooBar = fooElement.data('foo-bar'); // 42
// or
const fBar = fooElement.data()['foo-bar']; // 42

But after I upgraded jquery (to 3.0) I get this:

const fooElement = $('#foo');
const fooBar = fooElement.data('foo-bar'); // undefined
// or
const fBar = fooElement.data()['foo-bar']; // undefined

How can I fix this?

What changed?


Solution

  • What changed was that there is now a breaking change: .data() names containing dashes

    Which means that what you tried will no longer work!

    What you can do is this:

    const fooElement = $('#foo');
    const fooBar = fooElement.data('fooBar'); // 42
    // or
    const fBar = fooElement.data()['fooBar']; // 42
    

    This is because jquery now camelCases all "kebab-case" (jquery's word not mine) data attributes.

    What you can use (if you want), is the actual data attribute:

    const fooElement = document.getElementById('foo');
    const fooBar = fooElement.getAttribute('data-foo-bar');  // 42
    

    If you want to learn more about DOM attributes vs DOM properties you can read this.