HTML Appending with jQuery [closed]

HTML Appending with jQuery [closed]

To appending is so many way to do

I have 3 examples :

  1. $(".test1").append("<div>content#1</div>");

  2. $("<div>content#2</div>").appendTo(".test2");

  3. $("<div>", { text : "content#3" }).appendTo(".test3");

I think

  1. is easiest
  2. is same…
  3. is ???

Can you tell which one I should to do ? and tell me some bad thing , good thing pls…

It is more of context rather than which one is better.

You’ll only see performance differences in very extreme cases, not something you would notice on a typical web site.

Essentially they are of the same purpose: i.e. to append one element into another.

The difference between .append() and .appendTo() reveals itself as soon as you do method chaining.

var $whatIsThis = $(".test1").append("<div>content#1</div>");

$whatIsThis would remain to be $(".test1").

var $whatIsThis = $("<div>content#1</div>").appendTo(".test1");

$whatIsThis would instead be the <div> you’ve just created.

As I’ve mentioned method chaining, here’s an example

This below will hide .test1. Since the new <div> will be inside it, both will end up not visible.

$(".test1") // this is me
    .hide(); // hide me, I'm .test1

This below will hide only the new <div> you appended into .test1.

.test1 and anything else inside .test1 should remain visible.

$("<div>content#1</div>") // this is me
    .hide(); // hide me, I'm the new <div>

all the above three codes does the same things as long as append() is considered.. appendTo() appends to later mentioned selector ..and you might notice the difference of append() and appendTo() while chaining in terms of context

but considering the dynamically created elements , i would go for 3rd one.. coz that is cleaner and readable..

consider you need to create 5 divs or more.. creating it with method 1 and 2 would look


with third method it is cleaner and readable..

var div1=$("<div>", { text : "content#3" });
var div2=$("<div>",...); and so on..