Alex Rivera | Logout

Should I cache document.getElementById() in a variable or call it everytime?

Asked 2010-01-30T22:42:43.890
13

I'm having a lot of elements which are generated and referenced (mouseover, clicks, position changes) a lot of times.

I have the ID's of those elements at hand. Is it wise to store the document.getElementById(ID) calls in a variable, or is it faster/just as fast/slower to call document.getElementById() everytime?

var app = [];
var app.elements = []; 
//i can store ['id1', 'id2', 'id3']
//OR ['id1' => document.getElementById('id1'), 'id2' => document.getElementById('id2'), 'id3' => document.getElementById('id3')]
Edit
Report

2 Answers

10

You should of course reuse the reference where possible, but you might need to get a new reference in each function body.

Example:

var e1 = document.getElementById('id1');
e1.innerHTML = 'test';
e1.className = 'info';

If you keep references longer, you may find that they no longer work. If you for example get innerHTML for a part of the page and stores it back, all elements in that part is removed and recreated. If you had a reference to one of the elements in that part, that element no longer exists.

// This will recreate all elements inside the 'parent' element:
document.getElementById('parent').innerHTML += 'test';
answered 2010-01-30T22:49:47.290
3

getElementById returns an element node, which is essentially just a JavaScript object. You can assign this object to a variable, meaning that the variable will point to this object whenever you type that variable at a later stage. So,

var id1 = document.getElementById('id1');

id1 now refers to the DOM element with an id of id1. If no element was found with that id then document.getElementById returns null.

If the elements stay within the DOM and don't get replaced then it makes sense to store them in an array, so that you can reference them as many times as you want without any performance costs.

If it helps, you could create a simple function to do it for you:

function getElementsByIds( /* id1, id2 ... */ ) {

    var elems = [];

    for (var i = 0, l = arguments.length; i < l; i++) {
        elems[i] = document.getElementById(arguments[i]);
    }

    return elems;

}

app.elements = getElementsByIds('id1', 'id2', 'id3');
answered 2010-01-30T22:52:00.780

Your Answer