Method: 1. Use append() to insert elements to the "end" inside the div element, the syntax is "$("div").append(element)"; 2. Use prepend(), Elements can be inserted into the "beginning" inside the div element with the syntax "$("div").prepend(element)".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
jquery adds elements in div
1. Use the append() method
in In jQuery, we can use the append() method to insert content "at the end" inside the selected element.
Syntax:
$(A).append(B)
means inserting B at the end of A.
Example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> div{ height: 100px; background-color:orange; } </style> <script src="js/jquery-1.10.2.min.js"></script> <script> $(function () { $("#btn").click(function () { var $strong = "<strong>欢迎来到PHP中文网!</strong>"; $("div").append($strong); }) }) </script> </head> <body> <div>hello!</div><br /> <input id="btn" type="button" value="插入"/> </body> </html>
2. Use prepend() method
in In jQuery, we can use the prepend() method to insert content to the "beginning" inside the selected element.
Syntax:
$(A).prepend(B)
means inserting B at the beginning of A.
Example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> div{ height: 100px; background-color:orange; } </style> <script src="js/jquery-1.10.2.min.js"></script> <script> $(function () { $("#btn").click(function () { var $strong = "<strong>欢迎来到PHP中文网!</strong>"; $("div").prepend($strong); }) }) </script> </head> <body> <div>hello!</div><br /> <input id="btn" type="button" value="插入"/> </body> </html>
Related video tutorial recommendation: jQuery Tutorial (Video)
The above is the detailed content of How to add elements inside div with jquery. For more information, please follow other related articles on the PHP Chinese website!