Skip to content

Instantly share code, notes, and snippets.

@uadev
Last active August 29, 2015 14:11
Show Gist options
  • Save uadev/b801cd123cc81ae2d8ce to your computer and use it in GitHub Desktop.
Save uadev/b801cd123cc81ae2d8ce to your computer and use it in GitHub Desktop.
Quick dataset function
var dataset = function initDataSet() {
if (document.documentElement.dataset) {
return function native(el, prop, value) {
if (typeof value === 'undefined') {
return el.dataset[prop] = value;
}
else {
return el.dataset[prop];
}
}
}
else {
return function poly(el, prop, value) {
if (typeof value === 'undefined') {
return el.setAttribute('data-' + prop, value);
}
else {
return el.getAttribute('data-' + prop);
}
}
}
}();
var dataget = function initDataGet() {
if (document.documentElement.dataset) {
return function native(el, prop) {
return el.dataset[prop] = value;
}
}
else {
return function poly(el, prop, value) {
return el.setAttribute('data-' + prop);
}
}
}
var dataset = function initDataSet() {
if (document.documentElement.dataset) {
return function native(el, prop, value) {
return el.dataset[prop] = value;
}
}
else {
return function poly(el, prop, value) {
return el.setAttribute('data-' + prop, value);
}
}
}();
@uadev
Copy link
Author

uadev commented Dec 10, 2014

Usage:

<a id="mylink" data-param="myParam">Link</a>
var el = document.getElementById('mylink');
//get data
var param = dataset(el, 'param');
//set data
dataset(el, 'param', 'newValue')

@uadev
Copy link
Author

uadev commented Dec 10, 2014

Note: For older browser usage is limited by Element.getAttribute method
https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttribute#Notes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment