1.appendChild() 方法可向节点的子节点列表的末尾添加新的子节点。
实例一:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<ul id="myList"><li>Coffee</li><li>Tea</li></ul>
<p id="demo">单击按钮将项目添加到列表中</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
var node=document.createElement("LI");
var textnode=document.createTextNode("Water");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
</script>
<p><strong>注意:</strong><br>首先创建一个节点,<br> 然后创建一个文本节点,<br>然后将文本节点添加到LI节点上。<br>最后将节点添加到列表中。</p>
</body>
</html>
页面效果:
实例一是向ul中添加li项
2.appendChild() 方法从一个元素向另一个元素移动元素。
实例二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<select id="select1" multiple="multiple" size="10">
<option>左1</option>
<option>左2</option>
<option>左3</option>
<option>左4</option>
<option>左5</option>
</select>
<span>
<button onclick="toRight()">>></button>
<button onclick="toLeft()"><<</button>
</span>
<select id="select2" multiple="multiple" size="10">
<option>右1</option>
<option>右2</option>
<option>右3</option>
<option>右4</option>
<option>右5</option>
</select>
<script type="text/javascript">
var select1 = document.getElementById("select1");
var select2 = document.getElementById("select2");
function toRight() {
var childs = select1.childNodes;
for (var i = 0; i < childs.length; i++) {
if (childs[i].selected) {
select2.appendChild(childs[i]);
}
}
}
function toLeft() {
var childs = select2.childNodes;
for (var i = 0; i < childs.length; i++) {
if (childs[i].selected) {
select1.appendChild(childs[i]);
}
}
}
</script>
</body>
</html>
页面效果:
实例二是下拉框选项的移动
总结:
appendChild()方法是向节点添加最后一个子节点,也可以使用此方法从一个元素向另一个元素移动元素 。