Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 446
prakashstar42 Avatar asked Aug 26 '14 04:08

prakashstar42


3 Answers

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");
like image 157
jfriend00 Avatar answered Nov 15 '22 17:11

jfriend00


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

like image 38
aleha Avatar answered Nov 15 '22 19:11

aleha


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.

like image 3
romaroma Avatar answered Nov 15 '22 18:11

romaroma