Don't use innerHTML. It is non-standard, hard to work with if you have to do anything more advanced, and generally leads to poor code.
Instead, remove all elements, add a text node, and then set that text node's nodeValue to your desired text:
Code:
var Dom = function() {
function clear(el) {
while (el.hasChildNodes())
el.removeChild(el.firstChild);
return el;
}
function setText(el, text) {
return Dom.clear(el)
.appendChild(document.createTextNode(text))
.parentNode;
}
return {
clear: clear,
setText: setText
};
}();
Now, the problem occurs when selecting your element. Your 'random numbers' style is horrible because it means we have to search through every element in the document looking for one with an ID of /msg\d+/. Now, assuming you can rework that to look like this:
Code:
<div id="msg0" class="postbody">
<img src="./images/smilies/tongue.gif" alt=":p" title="tongue">
</div>
<div id="msg1" class="postbody">
Test!
</div>
<div id="msg2" class="postbody">
<img src="./images/smilies/biggrin.gif" alt=":)" title="biggrin">
</div>
... then we can do:
Code:
function() {
for (var i = 0, e; e = document.getElementById("msg" + i); ++i)
Dom.setText(e, "blah!");
}();
Otherwise, we really do have to check every element:
Code:
function() {
var a = document.getElementsByTagName("*")
|| document.all,
rx = /msg\d+/;
for (var i = 0, e; e = a[i]; ++i)
if (rx.test(e.id))
Dom.setText(e, "blah!");
}();
... which is a lot slower (as well as considerably more complicated).
Bookmarks