tags:

views:

3195

answers:

4

Is there a way to 'pre-build' a snippet of HTML before adding it to the DOM?

For example:

$mysnippet.append("<h1>hello</h1>");
$mysnippet.append("<h1>world</h1>");
$("destination").append($mysnippet);

where $mysnippet doesnt exist in the DOM. I'd like to dynamically build up some lumps of html and then insert them into the page at appropriate points later.

+6  A: 

Yes pretty much exactly how you have done it

Some extension of this...

$('<div>').attr('id', 'yourid').addClass('yourclass').append().append()...

and then finally

.appendTo($("#parentid"));
adam
+1  A: 

Sure, just build them as a string:

$mysnippet = "<h1>hello</h1>";
$mysnippet = $mysnippet + "<h1>world</h1>";
$("destination").append($mysnippet);
James Curran
A: 

There is a plugin for this:

http://plugins.jquery.com/project/appendText

GeekyMonkey
+16  A: 

When dealing with more complex nodes (especially heavily nested ones), it is a better approach to write the node in HTML and set its visibility hidden.

You can then use JQuery's clone() method to make a copy of the node and adapt its contents to your needs.

E.g. with this html:

<div class="template-node" style="display:none;">
   <h2>Template Headline</h2>
   <p class="summary">Summary goes here</p>
   <a href="#" class="storylink">View full story</a>
</div>

it's much faster and understandable to do:

var $clone = $('.template-node').clone();
$clone.find('h2').text('My new headline');
$clone.find('p').text('My article summary');
$clone.find('a').attr('href','article_page.html');
$('#destination').append($clone);

than to create the entire node in memory like shown above.

Franz
you forgot that you're appending the clone that's still hidden.. $('#destination').append($clone.show()) will fix that.
ajma
I find it helps to attach the display: none; to the template css class, and then by removing the class from the clone it displays the html when appended.
Kendall Hopkins