10
When modifying a certain initial value of data
from jQuery, I noticed the value of the dataset
is not modified.
So I drew up the following test:
HTML:
<div data-value="initial value" id="div-test-1"></div>
<div data-value="initial value" id="div-test-2"></div>
jQuery:
First test:
$(function(){
var $div1 = $('#div-test-1')
console.log($div1.data('value')); // intial value
$div1.data('value', 'new value');
console.log($div1.data('value')) // new value
console.log($div1.prop('dataset').value); // initial value
});
Second test:
$(function(){
var $div2 = $('#div-test-2');
console.log($div2.data('value')) ;// intial value
$div2.attr('data-value', 'new value');
console.log($div2.data('value')); // initial value
console.log($div2.prop('dataset').value); // new value
});
That is, for definitions made with data()
, values have been changed to jQuery, but not to the attribute dataset
; and, when modified in dataset
, are not returned by data()
as expected.
There is also another difference: We can define values of the type Number
, Array
and Object
through the data
jQuery. Already the dataset
DOESN’T DO THAT.
Behold:
Example with dataset
:
$('body').get(0).dataset.element = {nome: "wallace"};
console.log($('body').get(0).dataset.element) // [object Object]
Example with data
jQuery:
$('body').data('element', {nome: 'wallace'});
console.log($('body').data('element')); // {nome: 'wallace'}
- Based on this example, we can state that jQuery DOES NOT use jQuery
dataset
HTML5? - And if "yes" to the first question, is there any specific reason for him to do so?
- It’s safe to use the
dataset
in projects where I won’t use jQuery? - Because they behave differently with respect to the returned types?
Very well explained
– Wallace Maxters
Dude, I thought the
.data()
was just to recover values ofdata-attributes
, but also had never researched about it. : D– KaduAmaral