本文示範如何運用 JavaScript 的 appendChild 方法,在 DOM 樹中動態新增節點。
<html>
<head>
<script type="text/javascript">
function t(){
var nodep = document.createElement('p'); // 建立 p 節點
var art = document.createTextNode('你好,世界'); // 建立文字節點
var cont = document.getElementById('container'); // 取得目標容器
cont.appendChild(nodep); // 將 p 節點加入容器
nodep.appendChild(art); // 將文字節點加入 p 節點
}
</script>
<style type="text/css">
p{width:100px;height:100px;background:green;}
#container p{width:100px;height:100px;background:blue;}
</style>
</head>
<body>
<div id="container"><p>hello world</p></div>
<p>說兩句吧</p>
<hr />
<button onclick="t()" value="">增加節點</button>
</body>
</html>
透過 createElement 建立元素、createTextNode 建立文字,再用 appendChild 逐層掛載,就能輕鬆擴充頁面結構。希望本文對你的 JavaScript 程式設計有所幫助。