I was wondering if it was possible to assign values to an element object. In this case, I wish to assign the returns from the setTimeout() function to an object within an element object.
For example:
var elem = document.getElementById('target');
elem.timeouts = new Object();
elem.timeouts.sometimeout = setTimeout('...', 1000);
So I could then do:
clearTimeout(elem.timeouts.sometimeout);
I know this might seem bad practice etc, but is it possible or will it cause browsers to catch fire and turn on their user etc.
Thanks.
DOM elements are Host objects (aka non-native) and as such they can do almost anything they want. It’s not guaranteed that your expandos will work. In particular IE used to have problems with them. It’s highly recommended to read this article:
What’s wrong with extending the DOM by @kangax
(it is from one of the Prototype.js developers who experienced the drawbacks of such bad habits. They’ve rewritten the whole library just to save themselfs from more headaches)
Now if you add
uniqueIDto elements in non-IE browsers (IE has it by default) and then yourdatafunction becomes a simple lookup ~ O(1). The real information will be stored in a closure.It’s 2-4x faster than
jQuery.data(test)1.) Hash table
2.) Array
If you want to avoid expandos all together you can use an array to hold elements (but it’s slower)
Array.prototype.indexOf (fallback)
You’re welcome! 🙂