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

Native js adds nodes appendChild, insertBefore

PHPz
Release: 2018-10-10 15:11:48
forward
3422 people have browsed it

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>
Copy after login

The result is as follows:

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

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>
Copy after login

The result is as follows:

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

For more related tutorials, please visit JavaScript Video Tutorial

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template