Home >Web Front-end >JS Tutorial >JavaScript adds or deletes child nodes and child elements

JavaScript adds or deletes child nodes and child elements

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

When adding a child node or child element, you must first create the element (element node) , and then add it to the existing element node. The example is as follows:

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

<script>
var para=document.createElement("p");//创建需要增加的元素节点
var node=document.createTextNode("这是新段落。");//创建文本节点
para.appendChild(node);//将文本节点增加至创建的元素中

var element=document.getElementById("p1");//获取父节点
element.appendChild(para);//添加至父节点内
</script>

Delete the child When adding nodes or elements, the idea is similar to adding new ones:

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

<script>
var parent=document.getElementById("p1");//获取父节点元素
var child=document.getElementById("p1");//获取需要删除的节点元素
parent.removeChild(child);//通过父节点移除
</script>

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