I want a javascript function to get a data-attribute of an element. I want to use it on native JS' elements.
I've searched around for prototype getters, but I just cant wrap my head around how it works (javascript isnt my cup of tea yet).
What I want:
this.myCustomFunction('fooBar'); // the `this` element
document.getElementById('ExampleId').myCustomFunction('fooBar'); // another way of selecting
All examples I find are on objects which I create myself, I want one like the example above.
To provide the benchmark, here you can find the benchmark
If someone could give me a small example, and some explanation on how the code flows, that'd be great (or on how this is called, for future reference).
The first comment recommands me not to do things this way. I'll explain my goal a bit more, in case there is another solution. This is where I'm at now:
Object.prototype.cms_getDataAttr = function(dataname){
// IE upto 10 doenst work with dataset, so use the slower 'getAttribute'
if( typeof this.dataset == 'undefined'){
return this.getAttribute('data-'+dataname);
}
else{
// I want to use this one instead, benchmarked this is ALOT faster
return this.dataset.bigsrc;
}
}