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.

Sign up to request clarification or add additional context in comments.

6 Comments

you forgot that you're appending the clone that's still hidden.. $('#destination').append($clone.show()) will fix that.
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.
@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.
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 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
|
40

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 Comment

I'm finding that .wrap() does not work with in-memory/out-of-dom elements.
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.

Comments

0

Sure, just build them as a string:

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

2 Comments

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).
@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.
0

There is a plugin for this:

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

Comments

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

Which creates:

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

Comments

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);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.