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
wvarpp = document.createElement("div") //The following code is used to create the
var node=document.createTextNode("This is a new paragraph.")//Add a text node to the
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
<body> <div id="div1"> <p id="p1">这是一个段落。 </p> <pid="p2">这是另外一个段落。</p> </div> <script> var pp = document.createElement("div") //以下代码是用于创建<div>元愫 var node=document.createTextNode("这是新段落。")://为 <div>元素添加文本节点 pp.appendChild(node); //将文本节点添加到<div>元素中 var element=document.getElementById("div1"); //最后,在-一个已存在的元素中添加div元素。查找已存在的元素: element.appendChild(pp); //添加到已存在的元素中: </script> </body>
【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!