Skip to content

Instantly share code, notes, and snippets.

@bbatsche
Created September 29, 2014 22:50
Show Gist options
  • Save bbatsche/ac5d5b161294409c59b4 to your computer and use it in GitHub Desktop.
Save bbatsche/ac5d5b161294409c59b4 to your computer and use it in GitHub Desktop.
Demonstrate getting & setting data attributes of an element
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JQuery, YAY!</title>
</head>
<body>
<h1 id="heading" data-alt-heading="MAGIC">Example Page</h1>
<button type="button" id="swap-heading">Do The Thing!</button>
<script src="js/jquery-2.1.1.min.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function() {
$("#swap-heading").click(function() {
// grab the value of "data-alt-heading"
var newHeading = $("#heading").data('alt-heading');
// grab the current HTML content
var currentHeading = $("#heading").html();
// save the current HTML content in the data store
$("#heading").data('alt-heading', currentHeading);
// set the element HTML to the new heading
$("#heading").html(newHeading);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment