動態新增與刪除 HTML 節點,是 DOM 操作的常見需求。以下範例用按鈕觸發函式,在容器中新增或移除節點。
<button onclick="appendnode()">新增</button> <button onclick="removenode()">刪除</button><div id="result"></div>
<script> var i=0; function appendnode(){var o=document.createElement("div");o.innerHTML="test "+i;document.getElementById("result").appendChild(o);i++;} function removenode(){var x=document.getElementById("result");if(x.lastChild)x.removeChild(x.lastChild);} </script>