Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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')]
like image 742
Ropstah Avatar asked Jan 30 '10 22:01

Ropstah


1 Answers

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';
like image 183
Guffa Avatar answered Nov 09 '22 05:11

Guffa