Dataset vs .data - Difference?

I am reading some values ​​in data attribute fields. I have seen two simple ways to read data as shown below:

var webappData = document.getElementById('web-app-data'),
    rating = webappData.dataset.rating;

      

OR

var effectData = $('.effects-list li'),
    creative = effectData.filter('[data-creative]').data("creative");

      

My question is which ones have the best performance or are they really different?

I have a page with many data attributes that I access and I would like to use a method that has the best performance.

Any guidance on understanding the difference between the two would be appreciated. While I'm looking at performance on purpose, if there are other reasons to use one over the other, I'd love to know about that too.

+10


source to share


1 answer


dataset

is a native property of the element that contains data attributes, this is a new (ish) addition and as such is only supported in IE11 +, Chrome 8+, FF 6+, etc.

A more cross-browser solution should be to get the attribute directly

webappData.getAttribute('data-rating');

      


data()

is a jQuery method and does not use the HTML5 data attribute to set the inital value, if it doesn't exist internally, it has nothing to do with the dataset,

data()

stores any data passed to it in an internal jQuery-generated object, so this won't work for example



$(element).data('key', 'value');

element.dataset.key // undefined

      

since the data is not stored in attributes at all, but inside jQuery.
The jQuery equivalent to get and set the data attribute would beattr()

$(element).attr('data-key', 'value');

      


Native methods are probably faster, but since they are not very comparable to jQuery data()

it doesn't really matter, but for getting the data attribute I would think the fastest method with better browser support would be

var rating = webappData.getAttribute('data-rating');

      

+32


source







All Articles