When modifying a certain initial value of data
of jQuery, I noticed that the value of dataset
is not modified.
Then I wrote 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()
, the values have been changed for jQuery, but not for the dataset
attribute; and when changed in dataset
, are not returned by data()
as expected.
There is also another difference: We can set values of type Number
, Array
and Object
through data
of jQuery. dataset
does NOT do this.
See:
Example with dataset
:
$('body').get(0).dataset.element = {nome: "wallace"};
console.log($('body').get(0).dataset.element) // [object Object]
Example with data
of jQuery:
$('body').data('element', {nome: 'wallace'});
console.log($('body').data('element')); // {nome: 'wallace'}
- Based on this example, can we say that jQuery does NOT use
dataset
of HTML5? - And if "yes" to the first question, is there any specific reason for doing so?
- Is it safe to use
dataset
on projects where I'm not going to use jQuery? - Why do they behave differently in regards to returned types?