Question

Which one is better:

$('div').attr('data-stuff');

or

$('div').data('stuff');

After having a discussion in the comments on this thread, I'm interested to know which is better to use, if any.

Was it helpful?

Solution 2

Taking what all people have said into consideration, here is "the answer":

.data is better because:

  1. it's slightly shorter to type.
  2. It can protect you from possible future changes to data structure (although unlikely).

.attr is better because:

  1. it loads nearly 3 times faster.

I think I will continue using .attr myself, but thank you all for this information :)

OTHER TIPS

This is edging close to being "too opinion based" but in this case there is actually a solid reason.

Essentially when coding you should allow the library you are working with to do as much of the "heavy lifting" as possible. You should insulate your code from the underlying data as much as possible.

One way to do this is to use the most specific call available. In this case you have a method that already extracts the data and you just tell it the data you need. Using the more generic method to replicate that data extraction behavior should be avoided.

Doing this makes your code slightly shorter. It also makes it safer (for example there is no opportunity to typo 'data-' as 'dota-' or similar) and it means that if there are any fixes or hacks done in the library (for example to work around a browser limitation with a specific browser) then you will benefit from them.

It can also insulate you from future changes in the data structures behind a library, although in this case that's unlikely.

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