-2

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?

Shadow Wizard Says No More War
  • 64,101
  • 26
  • 136
  • 201
Naftali
  • 142,114
  • 39
  • 237
  • 299
  • check here, https://plnkr.co/edit/0g9ITDAouWBL7XYRZzAO?p=preview seems to be working fine with jquery 3.0 – Deep Jun 14 '16 at 14:34
  • @Deep That is odd as the object only contains fooBar: 42 plnkr.co/edit/eTxAPEXjUNi0b7RxUov7?p=preview . That must be something your browser is doing. – Naftali Jun 16 '16 at 16:01

1 Answers1

4

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.

Community
  • 1
  • 1
Naftali
  • 142,114
  • 39
  • 237
  • 299