Best practice for inserting large chunks of HTML into elements with Javscript?

Posted by hamstar on Stack Overflow See other posts from Stack Overflow or by hamstar
Published on 2010-05-15T11:00:10Z Indexed on 2010/05/15 11:04 UTC
Read the original article Hit count: 273

Filed under:
|
|
|

Hey guys. I'm building a web application (using prototype) at the moment that requires the addition of large chunks of HTML into the DOM. Most of these are rows that contain elements with all manner of attributes.

Currently I keep a blank row of html in a variable and

var blankRow = '<tr><td>'
    +'<a href="{LINK}" onclick="someFunc(\'{STRING}\');">{WORD}</a>'
    +'</td></tr>';

function insertRow(o) {
    newRow = blankRow
        .sub('{LINK}',o.link)
        .sub('{STRING}',o.string)
        .sub('{WORD}',o.word);
    $('tbodyElem').insert( newRow );
}

Now that works all well and dandy, but is it the best practice?

I have to update the code in the blankRow when I update code on the page, so the new elements being inserted are the same. It gets sucky when I have like 40 lines of HTML to go in a blankRow and then I have to escape it too.

Is there an easier way? I was thinking of urlencoding and then decoding it before insertion but that would still mean a blankRow and lots of escaping.

What would be mean would be a eof function a la PHP et al.

$blankRow = <<<EOF
text
text
EOF;

That would mean no escaping but it would still need a blankRow.

What do you do in this situation?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about dom