Please reply below trimmed quotes of the bits you are replying to.
One question that pops to my head now is that if I do end up using an
array to store id locations, if I make innerHTML replacements or
If you replace a node, then your stored reference is useless,
regardless of how you replaced the node. The best idea is to update
the reference at the same time you replace the node. I think you'll
have exaclty the same issue using IDs - you'll have to ensure either
the new node has the same ID as the one it is replacing, or that you
update your referencing scheme (which might be a list of IDs in an
array).
The use of innerHTML or DOM to create/replace the node just changes the
method used to maintain references. You may lean toward innerHTML
because in IE it is much, much faster than using DOM. But for other
browsers, DOM tends to be just as fast as innerHTML (in some it is
faster).
additions to other tags either before or after the div, do the
locations all go bad? In that case, it might be better to just use
getElementById all the time.
Modifing other parts of the DOM will not affect either method of
referencing an element.
For the sake of it, below is a simple test. Using an array of
references is much faster if you leave out building the array. If the
time taken to build the array is included, it is still a bit faster
than using getElementById every time.
So if your elements are reasonably static, then the stored references
is much faster (but only noticeably for more than say 100 elements in a
tight loop). If they aren't, it is still likely marginally faster to
update the array of references and use that. Incidentally, on my
machine, Firefox runs the following test in about 500 ms, IE takes
about 2500ms (that is, 5 times longer).
<script type="text/javascript">
function hideAllByID(){
var s = new Date();
var i = 0;
var x;
while ((x = document.getElementById('d' + i++))){
x.style.display = 'none';
}
var f = new Date();
alert('Using getElementById: ' + (f-s));
}
function hideAllByRef(){
var refArray = [];
var s = new Date();
var i = 0;
while ((x = document.getElementById('d' + i++))){
refArray.push(x);
}
var f = new Date();
var msg = 'Load reference array: ' + (f-s);
i = refArray.length;
s = new Date();
while (i--){
refArray
.style.display = 'none';
}
f = new Date();
msg += '\nHide elements: ' + (f-s);
alert(msg);
}
for (var i=0; i<1000; i++){
document.write('<div id="d' + i + '">div ' + i + '<\div>');
}
</script>