Home>Article>Web Front-end> What is the method to create a new node in javascript
The methods are: 1. createElement(), create element nodes; 2. createTextNode(), create text nodes; 3. createComment(), create comment nodes; 4. createDocumentFragment(), create document fragment nodes.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
(1)document.createElement(tagName)
createElement() is used to create an element node, that is, a node with nodeType=1. Among them, tagName is the name of the HTML tag, and a node object will be returned.
(2)document.createTextNode(text)
createTextNode() is used to create a text node, that is, a node with nodeType=3. Among them, text is the content of the text node, and a node object will be returned.
(3)document.createComment(comment)
createComment() is used to create a comment node, that is, a node with nodeType=8. Among them, comment is the content of the comment, and a node object will be returned.
(4)document.createDocumentFragment);
createDocumentFragment() is used to create document fragment nodes. Document fragment nodes are a collection of several DOM nodes, which can include various types of nodes, such as element nodes, text nodes, comment nodes, etc. The document fragment node is empty when it is initially created, and nodes need to be added to it.
For example, create the dc6dce4a544fdca2df29d5ac0ea9906b tag as follows:
wvarpp = document.createElement("div") //The following code is used to create the dc6dce4a544fdca2df29d5ac0ea9906b element:
var node=document.createTextNode("This is a new paragraph.")//Add a text node to the dc6dce4a544fdca2df29d5ac0ea9906b element:
pp.appendChild(node); //Add a text node to < ;div>Yuansuzhong:
var element=document.getElementById("div1"); //Finally, add the p element to an existing element. Find existing elements:
element.appendChild(pp); //Add to existing elements
Use insertBefore() method: add new elements to the starting position
这是一个段落。
这是另外一个段落。
【Recommended learning:javascript advanced tutorial】
The above is the detailed content of What is the method to create a new node in javascript. For more information, please follow other related articles on the PHP Chinese website!