jQuery / Vanilla JS with data attributes
by Ben Clayton
HTML
<div id="mydiv1">
</div>
<div id="mydiv2">
</div>
JavaScript
// Method 1
$("#mydiv1").attr("data-fred",1);
var el = document.getElementById('mydiv1');
alert("fred " + el.dataset.fred);
// Method 2 which DOES NOT WORK
// see jquery docs "Using the data() method to update data does not affect attributes in the DOM. To set a data-* attribute value, use attr."
$("#mydiv2").data("bert",2);
var el = document.getElementById('mydiv2');
alert("bert " + el.dataset.fred);