user1032531
user1032531

Reputation: 26311

Proper way to get data-attr value using jQuery

Is one way preferred over the other? If so, why? Or are there better ways?

var something=$('#something').attr('data-something');
var something=$('#something').data('something');

<p id='something' data-something='hello'>goodby</p>

Upvotes: 0

Views: 44

Answers (2)

IronFlare
IronFlare

Reputation: 2322

.data() is generally a more useful function because it can, among other things, parse data types. If you have an element with value data-something="15" and add 1 to it with .attr("data-something") + 1, you'll get 151, whereas if you use .data("something") + 1 you'll get 16. .data() can also parse booleans and JSON.

One drawback of .data() is that, as @Guffa noted, it doesn't actually modify DOM elements, so if you have other code that reads the new value of the attribute after .data() modifies it, you should use attr() instead.

.data() is overall a much more powerful and better function, but there are plenty of situations in which it is actually detrimental and the less-powerful .attr() should be used in its place.

http://api.jquery.com/data/#data-html5

Upvotes: 1

Guffa
Guffa

Reputation: 700650

That depends on what you want to get, they do different things.

.attr('data-something') will get you the initial value.

.data('something') will get you the current value.

If you use .data('something', 'goodbye') to change the value, after that using attr will get you 'hello' and data will get you 'goodbye'.

Upvotes: 3

Related Questions