HTML DOM appendChild() 方法

时间:2018-02-23 17:12:42   收藏:0   阅读:3174

1.

<!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);

//此时node为<li>Water</li>

//(不知为何 appendChild方法能将文本append到标签里)


document.getElementById("myList").appendChild(node);
}
</script>

<p><b>注释:</b>首先创建 LI 节点,然后创建文本节点,然后把这个文本节点追加到 LI 节点。最后把 LI 节点添加到列表中。</p>

</body>
</html>

 

 

 

 

2.

<!DOCTYPE html>
<html>
<body>

<ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
<ul id="myList2"><li>Water</li><li>Milk</li></ul>

<p id="demo2">demo2</p>
<p id="demo">请点击按钮把项目从一个列表移动到另一个列表中。</p>

<button onclick="myFunction()">亲自试一试</button>

<script>
function myFunction()
{
var node=document.getElementById("myList2").lastChild;

//这里倒像是把 <li>Milk</li> 剪切出来了
console.log(node);
document.getElementById("demo2").appendChild(node);

//然后再追加到这里
}
</script>

</body>
</html>

 

---------------------------------------------以上来源于W3School "HTML DOM appendChild() 方法" 一节

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!