37

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.

7 Answers 7

59

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.

6
  • 7
    you forgot that you're appending the clone that's still hidden.. $('#destination').append($clone.show()) will fix that.
    – ajma
    Apr 3, 2010 at 7:29
  • 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. Jun 29, 2010 at 16:45
  • 2
    @Niels it's a (perhaps somewhat exotic) convention that I use myself - variables holding jQuery-selectors are prefixed with $ to give them some jQuery "flavor" to help distinguish them from other local variables. Jun 5, 2012 at 12:37
  • 1
    What if I want to make a reusable javascript library? Where do I put the HTML template? You don't want to have to be adding extra html to every page that uses the library. Can't you store the HTML template as a literal in javascript somehow?
    – interstar
    Jul 1, 2012 at 12:41
  • 1
    @interstar Once you add html to javascript file you start mixing js with html. IMHO javascript templating is the way to go. Like one developed by John Resing
    – Peeech
    Mar 10, 2013 at 14:54
39

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"));
1
  • 3
    I'm finding that .wrap() does not work with in-memory/out-of-dom elements.
    – user982671
    Apr 17, 2013 at 16:32
9

Old thread but I bumped into it while searching for the same.

var memtag = $('<div />', {
                'class'    : 'yourclass',
                'id'       : 'theId',
                'data-aaa' : 'attributevalue',
                html       : 'text between the div tags'
});

memtag is now an in memory html tag, and can be inserted into the DOM if you want. If you do such thing with an img tag you can 'preload' images into the cache for later use.

0

Sure, just build them as a string:

$mysnippet = "<h1>hello</h1>";
$mysnippet = $mysnippet + "<h1>world</h1>";
$("destination").append($mysnippet);
2
  • 2
    Treating the DOM as text is hacky (the DOM isn't a string, it's just persisted as one), unreliable (it increases the chance of creating something unbalanced) and unnecessary (we have native methods and JQuery to make nodes). Mar 17, 2012 at 11:26
  • @mikemaccana Reading DOM creation code is a pain in the ass and DOM creation code is also slower than just giving it a string. Pick your battles. Aug 14, 2014 at 18:51
0

There is a plugin for this:

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

0
var sample =
    $('<div></div>')
        .append(
            $('<div></div>')
                .addClass('testing-attributes')
                .text('testing'))
        .html();

Which creates:

<div class="testing-attributes">testing</div>
0

You can prebuild it and also attach events, as well as data attributes, inner html, etc, etc.

var eltProps = {
    css: {
        border: 1,
        "background-color": "red",
        padding: "5px"
    },
    class: "bblock",
    id: "bb_1",
    html: "<span>jQuery</span>",
    data: {
        name: "normal-div",
        role: "building-block"
    },
    click: function() {
         alert("I was clicked. My id is" + $(this).attr("id"));
    }
};

var elt = $("<div/>", eltProps);

$("body").append(elt);

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.