37. Element appendChild() 方法

来源:互联网 发布:写安卓软件 编辑:程序博客网 时间:2024/05/21 06:01

实例

在列表中添加项目:document.getElementById("myList").appendChild(newListItem);添加之前:CoffeeTea添加之后:CoffeeTeaWater
<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></body>

定义和用法

appendChild() 方法向节点添加最后一个子节点

提示:如果您需要创建包含文本的新段落,请记得添加到段落的文本的文本节点,然后向文档添加该段落。

您也可以使用 appendChild() 方法从一个元素向另一个元素中移动元素。

<ul id="myList1"><li>Coffee</li><li>Tea</li></ul><ul id="myList2"><li>Water</li><li>Milk</li></ul><p id="demo">请点击按钮把项目从一个列表移动到另一个列表中。</p><button onclick="myFunction()">亲自试一试</button><script>function myFunction(){var node=document.getElementById("myList2").lastChild;document.getElementById("myList1").appendChild(node);}</script>
0 0
原创粉丝点击