Can't update data-attribute value
Use that instead, if you wish to change the attribute data-num of node element, not of data object:
DEMO
$('#changeData').click(function (e) {
e.preventDefault();
var num = +$('#foo').attr("data-num");
console.log(num);
num = num + 1;
console.log(num);
$('#foo').attr('data-num', num);
});
PS: but you should use the data() object in virtually all cases, but not all...
THE ANSWER BELOW IS THE GOOD ONE
You aren't using the data method correctly. The correct code to update data is:
$('#foo').data('num', num);
So your example would be:
var num = $('#foo').data("num") + 1;
console.log(num)
$('#foo').data('num', num);
console.log(num)
If we wanted to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute
and setAttribute
methods as shown below:
JavaScript
<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>
Through jQuery
// Fetching data
var fruitCount = $(this).data('fruit');
// Above does not work in firefox. So use below to get attribute value.
var fruitCount = $(this).attr('data-fruit');
// Assigning data
$(this).data('fruit','7');
// But when you get the value again, it will return old value.
// You have to set it as below to update value. Then you will get updated value.
$(this).attr('data-fruit','7');
Read this documentation for vanilla js or this documentation for jquery