Method: 1. Use "$(specified element).prepend(new element)" or "$(new element).prependTo(specified element)" to add elements at the beginning; 2. Use "$ (specified element).append(new element)" or "$(new element).appendTo(specified element)" to add elements at the end.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
Add elements inside the element, that is, add sub-elements to the specified element. There are four ways to add child elements in jquery:
prepend() and prependTo() methods: add child elements at the beginning of the specified element
append() and appendTo() methods: add sub-elements at the end of the specified element
1, use prepend() and prependTo () method
The prepend() and prependTo() methods both insert content into the "beginning" of the selected element, but the operating objects of the two are reversed.
$(A).prepend(B)
means inserting B at the beginning of A.
$(A).prependTo(B)
means inserting A into the beginning of B.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("div").prepend("<p>这是div块中的一个新段落。</p>"); $("<span>这是div块中的一个新元素。</span>").prependTo("div"); }); }); </script> </head> <body> <div style="background-color:yellow"> 这是一些文本。 <p>这是div块中的一个段落。</p> </div> <button>在div中增加元素</button> </body> </html>
2. Use the append() and appendTo() methods
append() and appendTo The () method inserts content "at the end" inside the selected element, but the operation objects of the two are reversed.
$(A).append(B)
means inserting B at the end of A.
$(A).appendTo(B)
means inserting A into the end of B.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("div").append("<p>这是div块中的一个新段落。</p>"); $("<span>这是div块中的一个新元素。</span>").appendTo("div"); }); }); </script> </head> <body> <div style="background-color:yellow"> 这是一些文本。 <p>这是div块中的一个段落。</p> </div> <button>在div中增加元素</button> </body> </html>
[Recommended learning: jQuery video tutorial, web front-end video】
The above is the detailed content of How to add elements inside elements in jquery. For more information, please follow other related articles on the PHP Chinese website!