I'm trying to make a function that gets all data-attributes dynamically from an element. For e.g.:
<button id="button" data-key1="title" data-key2="content">Button 1</button>
<button id="changeButtonData">Change data for button 1</button>
$(document).on('click', '#button', function(e){
e.preventDefault();
$buttonData = $(this).data();
console.log($buttonData);
}
$(document).on('click', '#changeButtonData', function(e){
e.preventDefault();
//edit existing data-keys value
$('#button').data('data-key1', 'newtitle');
//store new data-key on element
$('#button').data('data-key3', 'new');
}
The problem is, if i click the first button and check the console log, it will show data-key1="title" and data-key2="content"
And if i click the 2nd button afterwards, and click the first button again to fire the console logging again, it won't display the new replaced data-attributes or the new data-tags.
Anyone got an idea how to solve this?