I have resumed working on an old project, basically a web based controller for iTunes. I had a working version a few months ago but one day Apache decided not to let me create COM objects any more, so I scrapped it. The code was messy, the UI was horrid, and the AJAX implementation was problematic. So I started a new version, this time diving into YUI as my AJAX library (save some time by not re-inventing the wheel) and some new Javascript tricks to make the whole thing much better. Work always tends to go on and off with me, but I’ve spent a considerable amount of time on it within the last few days. So much that I found a new DOM annoyance.
This time, the deal is when adding nodes using the (not so standard) innerHTML method on an XHTML page, it is all kinds of bad to add your markup in different lines.
element.innerHTML = '<div id="title">';
element.innerHTML += '<div id="name">name</div>';
element.innerHTML += '<div id="artist">artist<.div>';
element.innerHTML += '</div>';
Turns out that at least Firefox 2 and Safari want to make sure I have valid XHTML markup and will auto close that <div id=”title”>. After spending some time in FireBug and on quirksmode I discovered this is by design and it is quiet easy to work around! Here it is.
var markup= '<div id="title">';
markup += '<div id="name">name</div>';
markup += '<div id="artist">artist</div>';
markup += '</div>';
element.innerHTML = markup;
Works like a charm. It seems that basically the browser ‘validates’ the string each time you set innerHTML, makes sence to me. Before you ask why I don’t stick with the W3C DOM, it is just because it is a pain to have to create each element one by one, and then create text nodes, and all that fun stuff. Not to mention when you start dealing with larger number of nodes it can get slow (as proven by quirksmode). There was an other suggestion, to use createContextualFragment(), and honestly I can’t see why that wouldn’t work either.