Differences between data() and attr('data') in jQuery

There are a key differences between data() and attr(), so if you work with jQuery and use HTML data tags, someday may you will face this: data() doesn’t work with the DOM or CSS. Why? Keep reading.

The solution, a short answer

This is because data() works with a local variable of jQuery and it does not update into the DOM, so the CSS does not apply either.

If you use attr('data-<em>whatever</em>'), it will work.

The differences

Keep in mind the differences between data() and attr(), let’s see:

  • data()- Can be objects (JSON)
  • Accesible only with data('whatever')
  • Not publicly visible
  • Faster and safer
  • attr()- Cannot be objects
  • Totally visible and accesible

Use wisely!

David Burgos

Read more posts by this author.