Home  >  Article  >  Web Front-end  >  Native js adds nodes appendChild, insertBefore

Native js adds nodes appendChild, insertBefore

PHPz
PHPzforward
2016-05-16 19:13:333398browse

1. createElement() creates element node
var element=document.createElement('element name');

2. crateTextNode() creates a text node
var txt=document.crateTextNode('text content');

3. createAttribute() creates an attribute node
var attr =document.createAttribute('attribute name');
attr.value='attribute value';

4. The appendChild() method adds the last child node to the node
As follows:

<p id="box" class="classa">
    <p id="p1">这是一个段落</p></p><script>
    var box=document.getElementById("box");    var p2=document.createElement("p");  //创建元素节点
    var txt=document.createTextNode("这是另一个段落"); //创建文本节点
    p2.appendChild(txt); //把创建的文本节点追加到元素节点中
    var attr=document.createAttribute("id"); //创建属性节点
    attr.value="p2"; //给属性节点设置值
    p2.setAttributeNode(attr); //给元素设置属性节点
    box.appendChild(p2);  //把创建的p元素追加到box最后
    console.log(box);</script>

The result is as follows:

<p id="box" class="classa">
    <p id="p1">这是一个段落</p>
    <p id="p2">这是另一个段落</p></p>

5. insertBefore() inserts a new child node before the specified child node
parent .insertBefore(newChild,oldChild);
is as follows:

<p id="box">
    <p id="p1">这是一个段落</p></p><script>
    var box=document.getElementById("box");    var p1=document.getElementById("p1");    var p0=document.createElement("p");    var txt=document.createTextNode("这是一个段落");
    p0.appendChild(txt);
    box.insertBefore(p0,p1);
    console.log(box);</script>

The result is as follows:

<p id="box">
    <p>这是一个新段落</p>
    <p id="p1">这是一个段落</p></p>

For more related tutorials, please visit JavaScript Video Tutorial

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete