Adding HTML with jQuery
To add so many ways to do
I have 3 examples:
$(".test1").append("<div>content#1</div>");$("<div>content#2</div>").appendTo(".test2");$("<div>", { text : "content#3" }).appendTo(".test3");
I think,
- easiest
- same...
- is ???
Can you tell me what I have to do? and tell me something bad, good things ...
This is more of a context than one that is better.
You will only see performance differences in very extreme cases, and not what you would notice on a typical website.
Essentially, they have the same goal: for example, add one element to another.
The difference between .append() and .appendTo() appears as soon as you execute the method chain.
var $whatIsThis = $(".test1").append("<div>content#1</div>"); $whatIsThis will remain $(".test1") .
var $whatIsThis = $("<div>content#1</div>").appendTo(".test1"); $whatIsThis instead be the <div> that you just created.
As I said, the chain of methods, here is an example
The following is a hiding of .test1 . Since the new <div> will be inside it, both of them will not be visible.
$(".test1") // this is me .append("<div>content#1</div>") .hide(); // hide me, I'm .test1 Below is just the new <div> added to .test1 .
.test1 and everything else inside .test1 should remain visible.
$("<div>content#1</div>") // this is me .appendTo(".test1") .hide(); // hide me, I'm the new <div> all of the above three codes perform the same actions as append() . appendTo() added to the selector mentioned above .. and you can notice the difference in append () and appendTo (), and the chain in terms of context
but given the dynamically generated elements, I would go for the third ... coz, which is cleaner and more readable.
consider that you need to create 5 div or more .. creating it using methods 1 and 2 will look messy
$(".test1").append("<div>content#1</div><div>aaa</div><div>sss</div>..."); with the third method, it is cleaner and more readable.
var div1=$("<div>", { text : "content#3" }); var div2=$("<div>",...); and so on.. A good append is faster than appendTo , but only for big changes. Otherwise, it does not matter.
The .append () and .appendTo () methods perform the same task. The main difference lies in the syntax, in particular, when placing content and goals. When using .append (), the selector expression preceding this method is the container into which the content is pasted. With .appendTo (), on the other hand, the content precedes the method, either as an expression of choice or as markup created on the fly, and it is inserted into the target container.
According to jquery documentation
So basically both append () and appendTo () do the same
I would prefer append () rather than appendTo ()