Home >Web Front-end >JS Tutorial >How to add elements in javascript
Method: 1. The appendChild() method inserts a new element at the end, with the syntax "appendChild(newchild)"; 2. The insertBefore() method, inserts a new element at the beginning with the new syntax "insertBefore(newchild,refchild)" ".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
There are two ways to insert new nodes (elements) in the document, one is to insert at the beginning, and the other is to insert at the end.
appendChild() method: Insert a new node at the end
JavaScript appendChild() method can be added to the end of the current node’s child node list new child node. The usage is as follows:
appendChild(newchild)
The parameter newchild represents the newly added node object and returns the newly added node.
Example 1
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p id="demo">单击按钮创建并添加p标签</p> <button onclick="myFunction()">点我</button> <script> function myFunction(){ var p=document.createElement("p"); var t=document.createTextNode("新添的p标签"); p.appendChild(t); document.body.appendChild(p); }; </script> </body> </html>
Rendering:
If the parameter node already exists in the document tree , it will be deleted from the document tree and reinserted in its new location. If the added node is a DocumentFragment node, it will not be inserted directly, but its child nodes will be inserted at the end of the current node.
Add an element to the document tree and the browser will render it immediately. Thereafter, any modifications made to this element will be reflected in the browser in real time.
insertBefore() method: Insert a new node at the beginning
JavaScript insertBefore() method can add to the beginning of the current node’s child node list new child node. The usage is as follows:
insertBefore(newchild, refchild)
The parameter newchild represents the newly inserted node, and refchild represents the node where the new node is inserted, which is used to specify the adjacent position behind the inserted node. After the insertion is successful, this method will return the newly inserted child node.
Example 2
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <ul id="myList"><li>Coffee</li><li>Tea</li></ul> <p id="demo">单击按钮插入一个项目列表</p> <button onclick="myFunction()">点我</button> <script> function myFunction(){ var newItem=document.createElement("LI") var textnode=document.createTextNode("Water") newItem.appendChild(textnode) var list=document.getElementById("myList") list.insertBefore(newItem,list.childNodes[0]); } </script> </body> </html> }
Rendering:
The above is the detailed content of How to add elements in javascript. For more information, please follow other related articles on the PHP Chinese website!