In the previous chapter, we also had a preliminary understanding of some operations on nodes. Now let's learn to insert
It is not enough to dynamically create elements. It is only temporarily stored in memory. Finally, we need to put page document and render it. So the question is, how to put it in the document?
This involves a positional relationship. It is common to put this newly created element inside it as a child element of a certain element on the page. For such processing, jQuery defines two operation methods
append: This operation is related to executing the native appendChild method on the specified elements and adding them to the document. The situation is similar.
appendTo: In fact, using this method reverses the conventional $(A).append(B) operation, that is, instead of appending B to A, appending A to B.
Note: The append() and .appendTo() methods have the same function. The main difference is the syntax - the location of the content and target is different.
Append() is preceded by the inserted object. , followed by the element content to be inserted into the object
The front of appendTo() is the element content to be inserted, and the following is the inserted object
Let’s explain in detail with examples:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title></title> <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> <style> .content { width: 300px; } .append{ background-color: blue; } .appendTo{ background-color: red; } </style> </head> <body> <button id="bt1">append添加</button> <button id="bt2">appendTo添加</button> <div class="content"></div> <script type="text/javascript"> $("#bt1").on('click', function() { //.append(), 内容在方法的后面, //参数是将要插入的内容。 $(".content").append('<div class="append">php 中文网</div>') }) </script> <script type="text/javascript"> $("#bt2").on('click', function() { //.appendTo()刚好相反,内容在方法前面, //无论是一个选择器表达式 或创建作为标记上的标记 //它都将被插入到目标容器的末尾。 $('<div class="appendTo">php.cn</div>').appendTo($(".content")) }) </script> </body> </html>