In a particular script I'm writing, I have a number of objects which are linked to some DOM Elements. Given that each element has a unique id, should each object keep just the element's id (and use document.getElementById each time), or store the element in a property?
Here's a simplified example of what I mean:
function myThing(elId) {
this.elId = elId;
}
myThing.prototype.getElValue = function() {
return document.getElementById(this.elId).nodeValue;
};
// -- vs -- //
function myThing(elId) {
this.el = document.getElementById(elId);
}
mything.prototype.getElValue = function() {
return this.el.nodeValue;
};
Does it make any difference? Are there any performance issues I should know about?
The easiest way to find an HTML element in the DOM, is by using the element id.
Any data for DOM elements is stored within the browser's memory for that tab, which it manages itself. Since your Javascript is just a part of that memory, it is in some way stored there.
The getElementById Method The most common way to access an HTML element is to use the id of the element.
I would store the element; it tends to make code clearer when you're not calling document.getElementById all the time, and though in your case you may not need to change IDs or allow elements without IDs, it's pretty common to want to do so.
(Unlike apphacker I wouldn't expect huge efficiency improvements from doing so, as getElementById tends to be fairly well-optimised in browsers.)
Are there any performance issues I should know about?
References from JavaScript objects to DOM objects are fine on their own, but when a DOM object has a link back to such a JavaScript object (usually through an event handler), you've got a reference cycle. This causes IE6-7 to leak memory as it fails to free up the cycled objects. For small simple apps you may not care. For complicated, long-running apps, you might have to work around the problem, for example by indirecting every event handler through a lookup map/array so there is no direct reference from the DOM object to the real event handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With