Home > Article > Web Front-end > How to dynamically create elements and append nodes with jQuery
We know that there are three ways to dynamically create elements in js. Elements can also be dynamically created in jQuery
For example:
var str = $("<a href='http://www.jb51.net'>脚本之家</a>"); $("ul").append(str); //将动态创建的str元素追加到ul下面
Append nodes
The methods to append nodes in js are appendChild (node element) and insertBefor (node element) , position), in jQuery it is
append appended after the last child node of the parent element
prepend inserted in front of the first child node of the parent element
after appended after the element, sibling
before element Append in front of, same level
The following code can be a good demonstration of appending nodes
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> div { width: 200px; height: 100px; border: 1px solid red; } </style> <script src="jquery-1.12.2.js"></script> <script> $(function () { //注意:如果传进来的jQuery对象是页面中存在的元素,它会这个对象剪切, // 所以我们会发现点击后,最下面的p标签被剪切了 var p1 = $("p"); $("#btn1").click(function () { $("div").append(p1); }); $("#btn2").click(function () { $("div").prepend(p1); }); $("#btn3").click(function () { $("div").after(p1); }); $("#btn4").click(function () { $("div").before(p1); }); }); </script> </head> <body> <input type="button" id="btn1" value="btnAppend"/> <input type="button" id="btn2" value="btnPrepend"/> <input type="button" id="btn3" value="btnAfter"/> <input type="button" id="btn4" value="btnBefore"/> <div>div标签1</div> <p>我要插队。。。</p> </body> </html>