Some stuff about Web and .NET development
RSS icon Email icon Home icon
  • What’s wrong with innerHTML ?

    Posted on April 24th, 2009 Thibaut 1 comment

    Every javascript developer knows innerHTML, that famous DOM property that allows you to set or get the HTML markup string of an element. It’s easy, it’s fast but it also kinda sucks. Here’s why :

    • It’s not a standard (it was originally introduced by Microsoft some time ago)
    • innerHTML is only a string with no structure. On the contrary, the DOM is a structured tree that allows to manipulate elements in a way cleaner manner. And you can put plenty of errors into that string without even getting a single warning from the Javascript
    • Maintenance is way much complicated if you have to dig into a complex HTML string than just inserting your line between the right CreateElement() methods of the DOM

    // Note how it’s easy with innerHTML to introduce errors

    // In this case, the div tag is not properly closed

    document.body.innerHTML = “<div>Some text</div”;

     

    // Now with the DOM, in a cleaner and more secure way

    var elt = document.createElement(“div”);

    var txt = document.createTextNode(“Some text”);

    elt.appendChild(txt);

    document.body.appendChild(elt);

    But… innerHTML isn’t completely bad though. In fact, it’s way faster than the DOM and is pretty well supported by browsers. So what should you do then ? There are loads of discussions on that topic on the web. In my opinion, you should always strive to respect the standards, which are primordial when you’re working for the web, but this must not slow down productivity either (by making some libraries or helpers for example). Now the big question : What are my alternatives to working with innerHTML ? This very interesting article will perfectly answer to that.

    Share/Save/Bookmark

     

    One response to “What’s wrong with innerHTML ?”

    1. A wonderful article…. this is just what I needed to read today. Thanks for describing the way you work and how you structure your writing projects. I’ll go read that article now.