Skip to content

Instantly share code, notes, and snippets.

@snowman-repos
Created October 3, 2012 05:43
Show Gist options
  • Save snowman-repos/3825249 to your computer and use it in GitHub Desktop.
Save snowman-repos/3825249 to your computer and use it in GitHub Desktop.
JavaScript: Element.dataset
/* Assuming element:
<div id="myDiv" data-name="myDiv" data-id="myId" data-my-custom-key="This is the value"></div>
*/
// Get the element
var element = document.getElementById("myDiv");
// Get the id
var id = element.dataset.id;
// Retrieves "data-my-custom-key"
var customKey = element.dataset.myCustomKey;
// Sets the value to something else
element.dataset.myCustomKey = "Some other value";
// Element becomes:
// <div id="myDiv" data-name="myDiv" data-id="myId" data-my-custom-key="Some other value"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment