Wednesday, September 12, 2007

using innerHTML with DOM methods

I tend to prefer to generate content following this pattern:


var html = [];
html.push('<h1>CONTENT!</h1>more content...');
...
el.innerHTML = html.join('');


In most cases in most browsers this is the fastest way to create markup it's a lot easier to grock the markup this way verses using DOM methods.

One issue I have with the approach is that you need a 'hook' element to dump the html into. This leads to a lot of empty nodes sitting around waiting for script to innerHTML them. Eventually, I stumbled on a way to avoid the hook elements and still have my innerHTML.

The key is to create a temp element

var temp = document.createElement('p');

us it to parse an html string

temp.innerHTML = '<h1>content!...</h1>';

then using DOM methods to insert the content

while( temp.childNodes.length > 0 )
el.parentNode.insertBefore(temp.childNodes[0], el);


Example:


var html = "<div>A lot of content...</div>";
var temp = document.createElement('p');
temp.innerHTML = html;
var el = document.getElementById('idOfElementToInsertBefore');
while( temp.childNodes.length > 0 )
el.parentNode.insertBefore(temp.childNodes[0], el);

0 comments: