Created
February 10, 2012 23:04
-
-
Save bunnymatic/1793847 to your computer and use it in GitHub Desktop.
give prototype the .data() method like jQuery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var PrototypeExtensions = { | |
| data: function(elem, key, val) { | |
| var DATA_REGEX = /data-(\w+)/; | |
| var ii = 0; | |
| var nattr = elem.attributes.length; | |
| if (key && val) { | |
| elem.setAttribute('data-' + key, val); | |
| } | |
| else { | |
| for (; ii < nattr; ++ii ) { | |
| var attr = elem.attributes[ii]; | |
| if (attr && attr.name) { | |
| var m = attr.name.match(DATA_REGEX); | |
| if (m && m.length > 1) { | |
| var datakey = m[1]; | |
| if (datakey === key) { | |
| return attr.value; | |
| } | |
| } | |
| } | |
| } | |
| } | |
| } | |
| }; | |
| Element.addMethods(PrototypeExtensions); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <div | |
| data-param1='the value for param1' | |
| data-otherstuff='other stuff value' | |
| id='dom_with_data'> | |
| This dom element had data | |
| </div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var val1 = $('dom_with_data').data('param1'); | |
| console.log(val1); | |
| // >> the value for param1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just an observation, the jQuery
data()functio returns an array of all data attributes if no key is specified, am I wrong or does the above only return null if there's no key set?My suggestion :
Disclaimer : I wrote this suggestion in like 2 minutes in BBcode, I didn't fiddle it or otherwise check if the JS is even valid! But you get my gist right?