A tip on avoiding innerHTML

Not that innerHTML should be avoided at all cost, but I’m currently in a purist kinda mood. Generally I like to avoid proprietary functions whenever possible. Now, sometimes it just makes sense to dip into Microsoft’s old trick-bag and pull this out.

Anyway, as I was making my way through Jeremy Keith’s amazing book, Bulletproof Ajax, this tip came up again and again. It’s not exactly a new trick, but it’s new to me, and it might help out a fellow javascripter:

Let’s say you have a target with a bunch of child elements:

<div id="target">
  <p>I am an example.</p>
  <a href="#">I am also an example.</a>
  <img src="example.gif" alt="I am yet another example." />
</div>

Let’s face it, the easy way to replace those child elements is with innerHTML:

target.innerHTML = newValue;

However, there’s also an easy way to replace the child elements using W3C approved methods:

while (target.hasChildNodes()) target.removeChild(target.lastChild);
target.appendChild(newValue);

Easy as pie! The while loop will continue as long as there’s a child node present. Out go the children, in goes the new value. No fuss, no muss.

del.icio.us:A tip on avoiding innerHTMLdigg:A tip on avoiding innerHTML

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*