Methods to add elements: 1. Use append(), the syntax "$("body").append(new element)" to add elements to the end of the body; 2. Use prepend() , the syntax "$("body").prepend(new element)" can add elements to the beginning of the body.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
Adding elements to the body means adding sub-elements to the body. The following article will introduce to you two methods of adding child elements to the body using jquery.
Method 1: Use append()
Use prepend() method to insert content (element or text) to the "beginning" inside the body element
Syntax:
$("body").append(新元素)
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(function() { $("button").click(function() { var newp = "<p>一个新段落</p>"; $("body").append(newp); }) }) </script> </head> <body style="background-color: #FF0000;"> <button>(body元素)在body中增加元素</button> </body> </html>
Method 2: Use prepend()
Use the prepend() method to insert content to the "beginning" inside the selected element.
Grammar:
$("body").prepend(新元素)
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(function() { $("button").click(function() { var newp = "<p>一个新段落</p>"; $("body").prepend(newp); }) }) </script> </head> <body style="background-color: #FF0000;"> <button>(body元素)在body中增加元素</button> </body> </html>
[Recommended learning: jQuery video tutorial, web front-end video】
The above is the detailed content of How to add elements to body in jquery. For more information, please follow other related articles on the PHP Chinese website!