I have this Html code that in the each paragraph tag has two data attributes 'data-tag' and 'data-name'. I also have two buttons, 'Show Data' and 'Set Data'.
The Show Data button displays the paragraph data attributes on console correctly.
When I click on Set Data, it should change all paragraph tags with the data attribute 'tag' to 'Complete' but it's not working. What am I doing wrong?
$("document").ready(function() {
// Shows data attributes in console - WORKING
$("#showdata").click(function() {
$("p").each(function() {
var tag = $(this).data("tag");
var name = $(this).data("name");
console.log(tag);
console.log(name);
});
});
// Change data attibute 'tag' - NOT WORKING
$("#setdata").click(function() {
$("p").each(function() {
$(this).data("tag", "Complete");
console.log($(this).data("tag"));
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<p data-tag="tag1" data-name="p1">Item 1</p>
<p data-tag="tag2" data-name="p2">Item 2</p>
<p data-tag="tag3" data-name="p3">Item 3</p>
<button class="button" id="showdata">Show data</button>
<button class="button" id="setdata">Set data</button>