Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 375
l2aelba Avatar asked Mar 24 '23 04:03

l2aelba


2 Answers

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
    .append("<div>content#1</div>")
    .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
    .appendTo(".test1")
    .hide(); // hide me, I'm the new <div>
like image 133
Terry Young Avatar answered Mar 31 '23 18:03

Terry Young


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 messy

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

with third method it is cleaner and readable..

var div1=$("<div>", { text : "content#3" });
var div2=$("<div>",...); and so on..
like image 44
bipen Avatar answered Mar 31 '23 17:03

bipen