prakashstar42
prakashstar42

Reputation: 687

jQuery create and append multiple elements

I have created 2 divs, Div1(freeze) Div2(parent) and again 3 divs(loading, header, msg) appended it to Div2(parent). Entire divs in to body tag. Below are my code, I think there is some other best way to achieve this.

    var freeze = $('<div/>',{
        "class" : "freeze"
    });
    var parent = $('<div/>',{
        "class":"parent"
    });

    var loading = $('<div/>',{
        "class":"loadimg"
    }).appendTo(parent);

    var header = $('<div/>',{
        "class":"header"
    }).appendTo(parent);
    var msg = $('<div/>',{
        "class":"msg"
    }).appendTo(parent);

    $('body').append(freeze,parent);

Upvotes: 31

Views: 85467

Answers (4)

romaroma
romaroma

Reputation: 658

jQuery methods often implement the decorator pattern which means you can nest calls:

el = $('<div>').addClass('parent')
       .append(
         $('<div>').addClass('loadimg')
       );

In this example, you add a child div to some parent div. You may use more .append here and decorate them with addClass, attr, and many other jQuery methods.

The developer of jQuery already did the hard work implementing the decorator pattern, it is time to honor their efforts and start using it.

Upvotes: 3

DamnScandalous
DamnScandalous

Reputation: 102

Please use symbol backtick '`' in your front and end of html string, this is so called template literals, now you able to write pure html in multiple lines and assign to variable.

Example >> var htmlString =

`

Your

HTML

`

Upvotes: 1

aleha_84
aleha_84

Reputation: 8539

Since the question is about creating and appending multiple objects at the same time using jQuery, here is an approach:

$('body').append([
    $('<div/>',{ "class": "freeze" }),
    $('<div/>',{ "class": "parent" }).append([
        $('<div/>',{ "class": "loadimg" }),
        $('<div/>',{ "class": "header" }),
        $('<div/>',{ "class": "msg" })
    ]);
]);

In some cases operating with structural data is more reliable and more convenient than raw markup

Upvotes: 42

jfriend00
jfriend00

Reputation: 707148

Using jQuery for most of this is complete overkill and just makes the code longer than necessary. Since everything you have is a constant, you can just create a single string of HTML and append that to the body.

If you want jQuery references to parts of it for later use, then just use .find() to find them later.

For example, you could just do this:

var html = '<div class="freeze"></div>' + 
           '<div class="parent">' + 
               '<div class="loadimg"></div>' +
               '<div class="header"></div>' +
               '<div class="msg"></div>' +
           '</div>';
$(document.body).append(html);

For later references, you can do something like this:

var header = $(document.body).find(".header");

Upvotes: 39

Related Questions