Home > Article > Web Front-end > How to add child nodes in front with jquery
Methods to add child nodes in front: 1. Use prepend() to insert a child node at the beginning of the selected element, the syntax is "$(element).prepend(child node)"; 2. Use rependTo (), you can insert the child node at the beginning of the specified element, the syntax is "$(child node).prependTo(element)".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
There are two ways to add child nodes in front of jquery:
prepend( )
prependTo( )
jQuery prepend() method
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"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(function () { $("#btn").click(function () { var $li = "<li>香蕉</li>"; $("ul").prepend($li); }) }) </script> </head> <body> <ul> <li>苹果</li> <li>梨子</li> <li>橘子</li> </ul> <input id="btn" type="button" value="插入" /> </body> </html>
jQuery prependTo() method
In jQuery, prependTo( ) and prepend( ) are similar in function. They both insert content into the "beginning" of the selected element, but their operation objects are reversed.
Syntax:
$(A).prependTo(B)
means inserting A into the beginning of B.
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(function () { $("#btn").click(function () { var $li = "<li>榴莲</li>"; $($li).prependTo("ul"); }) }) </script> </head> <body> <ul> <li>香蕉</li> <li>苹果</li> <li>梨子</li> <li>橘子</li> </ul> <input id="btn" type="button" value="插入" /> </body> </html>
Explanation:
prepend() and prependTo() have similar functions but different operations On the contrary, many novices are easily confused. However, if we carefully consider the English meaning of "to", it is easy to distinguish. prepend() means inserting content into the element, and prependTo() means inserting content into the "(to)" element.
[Recommended learning: jQuery video tutorial, web front-end development]
The above is the detailed content of How to add child nodes in front with jquery. For more information, please follow other related articles on the PHP Chinese website!