純原生 JavaScript 實現節點動態新增與移除,無需框架依賴。核心 API 包含 document.createElement、appendChild、removeChild 與 lastChild 屬性。
<input type="button" onclick="appendNode()" value="新增節點">
<input type="button" onclick="removeNode()" value="刪除節點">
<div id="result"></div>
<script>
let i = 0;
function appendNode() {
const el = document.createElement("div");
el.textContent = "test" + i++;
document.getElementById('result').appendChild(el);
}
function removeNode() {
const container = document.getElementById('result');
if (container.lastChild) container.removeChild(container.lastChild);
}
</script>
createElement 建立新元素節點textContent 設定純文字內容(避免 XSS 風險)appendChild 掛載至容器末尾lastChild 取得最後子節點,配合 removeChild 移除if (container.lastChild) 避免空容器報錯insertBefore 實現指定位置插入classList 動態切換樣式DocumentFragment 批次操作提升效能