1.appendChild() 方法:可以向节点的子节点列表的末尾添加新的子节点。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<ul id="myList">
<li>篮球</li>
<li>足球</li>
</ul>
<button onclick="myFunction()">添加</button>
<script type="text/javascript">
function myFunction() {
var node = document.createElement("LI");
var textnode = document.createTextNode("乒乓球");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
</script>
</body>
</html>
</body>
</html>
2.insertBefore() 方法:可在已有的字节点前中插入一个新的子节点。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<ul id="myList">
<li>篮球</li>
<li>足球</li>
</ul>
<button onclick="myFunction()">点我</button>
<script type="text/javascript">
function myFunction() {
var newItem = document.createElement("LI")
var textnode = document.createTextNode("乒乓球")
newItem.appendChild(textnode)
var list = document.getElementById("myList")
list.insertBefore(newItem, list.childNodes[0]);
}
</script>
</body>
</html>