jQuery - Add elements
Add new HTML content
We will learn four jQuery methods for adding new content:
append() - Insert content at the end of the selected element
prepend() - Insert content at the beginning of the selected element
after() - Insert content after the selected element
before() - Insert content before the selected element
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("p").append(" <b>追加文本</b>。"); }); $("#btn2").click(function(){ $("ol").append("<li>追加列表项</li>"); }); }); </script> </head> <body> <p>段落。</p> <p>另一个段落。</p> <ol> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> </ol> <button id="btn1">添加文本</button> <button id="btn2">添加列表项</button> </body> </html>
prepend() method
jQuery prepend() method inserts content at the beginning of the selected element.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("p").prepend("<b>在开头追加文本</b>。 "); }); $("#btn2").click(function(){ $("ol").prepend("<li>在开头添加列表项</li>"); }); }); </script> </head> <body> <p>段落。</p> <p>另一个段落。</p> <ol> <li>列表 1</li> <li>列表 2</li> <li>列表 3</li> </ol> <button id="btn1">添加文本</button> <button id="btn2">添加列表项</button> </body> </html>
The append() and prepend() methods can receive an unlimited number of new elements via parameters. Text/HTML can be generated via jQuery (like in the example above), or via JavaScript code and DOM elements.
after() and before()
jQuery after() method inserts content after the selected element.
The jQuery before() method inserts content before the selected element.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("span").before("<b>之前</b>"); }); $("#btn2").click(function(){ $("span").after("<i>之后</i>"); }); }); </script> </head> <body> <span style="font-size: 30px;">内容</span> <br><br> <button id="btn1">之前插入</button> <button id="btn2">之后插入</button> </body> </html>
The after() and before() methods can receive an unlimited number of new elements through parameters. New elements can be created via text/HTML, jQuery or JavaScript/DOM.