DIV CSS 佈局教程網

搞懂 appendChild 與 insertBefore:DOM 節點插入的兩種方式
編輯:關於JavaScript     

先看定義

  • appendChild(newchild):在節點的子節點列表末尾加入新的子節點
  • insertBefore(newchild, refchild):在既有的某個子節點之前插入新的子節點

相同之處:兩者都是插入子節點。不同之處在於定位依據——appendChild 相對於「父節點」說話(永遠放最後),insertBefore 相對於「兄弟節點」說話(放在指定節點前面)。

基礎範例

<div class="btns">
<input type="button" value="插入元素" id="creatbtn" />
</div>

<div id="box-one">
<p class="con2" id="p1">1</p>
<p class="con2">2</p>
<p class="con2">3</p>
</div>
window.onload = function () {
  var btn = document.getElementById("creatbtn");
  btn.onclick = function () { insertEle(); };
}

function insertEle() {
  var oTest = document.getElementById("box-one");
  var newNode = document.createElement("div");
  newNode.innerHTML = " This is a newcon ";

  // 以下兩種寫法都能把節點放到列表末尾
  oTest.appendChild(newNode);
  oTest.insertBefore(newNode, null);
}

這裡有個關鍵點:insertBefore(node, null) 的效果等同於 appendChild(node)。當第二個參數為 null 時,新節點會被放到最後。

插入到指定位置

function insertEle() {
  var oTest = document.getElementById("box-one");
  var newNode = document.createElement("div");
  var reforeNode = document.getElementById("p1");
  newNode.innerHTML = " This is a newcon ";

  oTest.insertBefore(newNode, reforeNode); // 插入到 id 為 p1 的元素「前面」
}

想插在 p1 後面呢?把參照點換成它的下一個兄弟即可:

function insertEle() {
  var oTest = document.getElementById("box-one");
  var newNode = document.createElement("div");
  var reforeNode = document.getElementById("p1");
  newNode.innerHTML = " This is a newcon ";

  oTest.insertBefore(newNode, reforeNode.nextSibling);
  // 插到 p1 的後面節點之前,等效於插在 p1 之後
}

關於 nextSibling 與 previousSibling

  • nextSibling:某元素之後緊鄰的同層節點
  • previousSibling:某元素之前緊鄰的同層節點

這裡有個容易踩到的陷阱:sibling 系列取得的是所有同層節點,包含文字節點與空白。由於 HTML 裡換行與縮排也會產生文字節點,p1.nextSibling 很可能是一個空白文字節點而不是你想像的那個 <p>。若只想取得元素節點,請改用 nextElementSibling / previousElementSibling,或用 children 集合。

歸納一下:insertBefore 的定義是「在某子節點前插入」,但搭配 nextSibling 靈活組合之後,它其實可以插入到子節點列表的任意位置。有些方法的能力往往超出定義字面,符合語法就能湊出意料之外的用法。

身為初學者懂得不多,理解或許也還淺,若有錯誤歡迎指正——記錄點滴並吸收建議,才能慢慢長大。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved