Skip to content

Instantly share code, notes, and snippets.

@Yuffster
Created July 25, 2012 05:48
Show Gist options
  • Save Yuffster/3174627 to your computer and use it in GitHub Desktop.
Save Yuffster/3174627 to your computer and use it in GitHub Desktop.
Data attribute API extension for MooTools.
Element.implement({
getData: function() {
var data = {}, attrs = this.attributes;
for (var i=0; i<attrs.length; i++){
k = attrs.item(i).nodeName;
if (k.match(/^data-/)) data[k.replace(/^data-/, '')] = attrs.item(i).nodeValue;
} return data;
},
clearData: function() {
var self = this;
Object.each(this.getData(), function(v,k){
self.removeProperty('data-'+k, '');
});
return this;
},
setData: function(k,v) {
this.setAttribute('data-'+k, v);
return this;
}
});
@assertchris
Copy link

element.get("data-hello")...? :)

@Yuffster
Copy link
Author

That's useful for when you're working with single data keys. ;) If you notice, the entire thing is just a thin wrapper over get[Attribute] to begin with, so I'm totally with you there.

I wrote this because I've been attaching "arbitrary" data attributes to elements which I needed to process and clear periodically, so the main benefit of this is to return just the custom data attributes without the data- prepended so I don't have to do the key translation each time and I can work with them procedurally rather than manually.

The setData is the only borderline useless method, but I like having symmetry in APIs. :)

@assertchris
Copy link

Wouldn't it be grand to have an element wrapper which mimics the .data attributes in the spec, using timers or property change events? :)

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