How to add sibling nodes in jquery: 1. Use before(), the syntax "$(specified element).before(sibling node)", you can insert sibling nodes before the specified element; 2. Use after() , the syntax "$(specified element).after(sibling node)" allows you to insert sibling nodes after the specified element.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
In jquery, you can use the following two methods to add sibling nodes
before() method: Insert specified content before the selected element.
after() method: Insert the specified content after the selected element.
1. Use before() to add sibling nodes forward
before() can insert sibling nodes before the specified element
Syntax:
$(A).before(B)
means inserting the B sibling node in front of the A node.
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(function () { $("button").click(function () { var a = "<span style='color:red;'>一个span元素</span>"; $("div").before(a); }) }) </script> </head> <body> <h1>一个大标题</h1> <p>一个p段落</p> <div>一个div元素</div> <p>一个p段落</p> <button>在div前插入一个兄弟节点</button> </body> </html>
2. Use after() to add sibling nodes backwards
after() can insert sibling nodes after the specified element
Syntax:
$(A).after(B)
means inserting the B sibling node after the outside of the A node.
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(function () { $("button").click(function () { var a = "<span style='color:red;'>一个span元素</span>"; $("div").after(a); }) }) </script> </head> <body> <h1>一个大标题</h1> <p>一个p段落</p> <div>一个div元素</div> <p>一个p段落</p> <button>在div前插入一个兄弟节点</button> </body> </html>
[Recommended learning: jQuery video tutorial, web front-end video 】
The above is the detailed content of How to add sibling nodes in jquery. For more information, please follow other related articles on the PHP Chinese website!