Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing references to DOM elements

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?

like image 308
nickf Avatar asked Apr 16 '09 01:04

nickf


People also ask

What is the best way to locate an element in the DOM?

The easiest way to find an HTML element in the DOM, is by using the element id.

Where is DOM stored?

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.

Which of the DOM methods listed uses an ID to find a page element?

The getElementById Method The most common way to access an HTML element is to use the id of the element.


1 Answers

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.

like image 170
bobince Avatar answered Nov 08 '22 00:11

bobince