Home > Web Front-end > JS Tutorial > body text

JavaScript adds or deletes child nodes and child elements

PHPz
Release: 2018-10-10 15:06:33
forward
1841 people have browsed it

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

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

For more related tutorials, please visit JavaScript Video Tutorial

Related labels:
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