87,907
社区成员
发帖
与我相关
我的任务
分享
<!DOCTYPE html>
<html>
<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);*/
//document.getElementsByTagName("UL")[0].appendChild(node);
//上面这种就是不会删除原有的节点,只会在最后面添加相关的节点
//代码片段二
var textnode=document.getElementsByTagName("li")[0];
/*console.log(textnode);
debugger;*/
document.getElementsByTagName("UL")[0].appendChild(textnode);
//
}
</script>
<p><b>注释:</b>首先创建 LI 节点,然后创建文本节点,然后把这个文本节点追加到 LI 节点。最后把 LI 节点添加到列表中。</p>
</body>
</html>