Date: Sun, 26 May 2013 10:06:07 +0200
- Blogger Hacked
To innerHTML or not to innerHTML
- Is innerHTML an angel or the devil?
There are two faces of innerHTML.
On one hand, it’s proprietary. It's certainly not part of the W3C DOM specifications. It’s also not very robust. It takes a single argument - a string - and squeezes that into the element, regardless of whether the string contains well-formed markup or not. Heck, it doesn't even check if the markup has a closing tag, and is often the reason for baffling layout bugs. It is very dangerous compared to the standard DOM methods - createElement, createTextNode and appendChild.
On the other hand, innerHTML reduces the lines of code. It is easy to write, if you can stand the trouble of escaping characters in the string. It is very well-supported. In fact, it enjoys better cross-browser support that DOM methods don't have. It also is faster than DOM. This is a proven fact.
To use or not to use innerHTML...That's a definite toughie to answer!
I have to admit that I always have been tempted to use innerHTML through and through. I just can't stand the clumsy extra lines needed with DOM and all the variables declared.
It is much easier to use innerHTML when it comes to Ajax. It even is a part of a microformat - the AHAH.
It’s the simplest way of taking the responseText property of the XMLHttpRequest object and inserting it into a specified part of a page.
And it reduces the LOC (Lines of code) by at least 3 times.
innerHTML does look dirty. But there’s no way to make Ajax work without making some sort of trade-off with non-standard technologies.
Followers of the DOM standards would say not to follow innerHTML. As a programmer, even I shouldn't. innerHTML is a bad programming practice, just like using magic numbers in a piece of code. But I'm tempted. I think innerHTML makes my life easier. Only I have to be a little careful. I keep following innerHTML because, standard or not, innerHTML is gonna stay.
The confusion haunts me forever.