JavaScript增加和删除DOM节点
创建节点
var p = createElement(element); // 创建标签
var text = document.createTextNode(“文本节点”); // 创建文本节点
p.appendChild(text); // 将文本节点添加到新创建的p标签中
<body>
<div id="main">
</div>
<script>
window.onload = function () {
var p = document.createElement("p");
var text = document.createTextNode("this is new element");
p.appendChild(text);
var main = document.getElementById("main");
main.appendChild(p);
}
</script>
</body>
或
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<button onclick="add()" type="button">添加</button>
<div id="box">
</div>
<script>
// 获取id为box的标签
div =document.querySelector('#box');
// 节点添加事件
function add(){
var input = document.createElement("input");
input.setAttribute('type', 'text');
div.appendChild(input);
};
</script>
</body>
</html>
在所选子节点插入新节点
insertBefore()
<body>
<div id="main">
<p id="p1">我是第一行</p>
<p id="p2">我是第二行</p>
<p id="p3">我是第三行</p>
</div>
<script>
window.onload = function () {
var p = document.createElement("p");
var text = document.createTextNode("我是插入的文本");
p.appendChild(text);
var main = document.getElementById("main");
var child = document.getElementById("p2");
main.insertBefore(p,child);
}
</script>
</body>
移除所选子节点
removeChild(child)
<body>
<div id="main">
<p id="p1">我是第一行</p>
<p id="p2">我是第二行</p>
<p id="p3">我是第三行</p>
</div>
<script>
window.onload = function () {
var parent = document.getElementById("main");
var child = document.getElementById("p3");
parent.removeChild(child);
}
</script>
</body>
或者
<body>
<div id="main">
<p id="p1">我是第一行</p>
<p id="p2">我是第二行</p>
<p id="p3">我是第三行</p>
</div>
<script>
window.onload = function () {
var child = document.getElementById("p2");
child.parentNode.removeChild(child);
}
</script>
</body>
替代所选子节点
replaceChild(para, child)
<body>
<div id="main">
<p id="p1">我是第一行</p>
<p id="p2">我是第二行</p>
<p id="p3">我是第三行</p>
</div>
<script>
window.onload = function () {
var p = document.createElement("p");
var text = document.createTextNode("我是刚替代完的节点");
p.appendChild(text);
var parent = document.getElementById("main");
var child = document.getElementById("p1");
parent.replaceChild(p,child);
}
</script>
</body>
还没有评论,来说两句吧...