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);
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");
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With