DIV CSS 佈局教程網

appendChild、insertBefore,以及自己動手做的 insertAfter
編輯:關於JavaScript     

appendChild

簽名:appendChild(newChild: Node) : Node

把一個節點加入目標節點的子節點清單,作為最後一個子節點。支援 IE 5.0+、Mozilla 1.0+、Netscape 6.0+、Safari 1.0+、Opera 7.0+。

target.appendChild(newChild);
var newElement = document.createElement('label');
newElement.setAttribute('value', 'Username:');
var usernameText = document.getElementById('username');
usernameText.appendChild(newElement);

insertBefore

在既有的某個子節點之前插入新節點。

target.insertBefore(newChild, existingChild);

其中 existingChild 若傳入 null,效果等同 appendChild。

var oTest = document.getElementById("test");
var newNode = document.createElement("p");
newNode.innerHTML = "This is a test";
oTest.insertBefore(newNode, oTest.childNodes[0]);

insertAfter:標準 API 裡沒有,自己補一個

W3C 的 DOM 規格並未提供 insertAfter。思路很單純:如果目標已經是最後一個子節點,就走 appendChild;否則用 insertBefore 插到目標的下一個兄弟節點之前。

function insertAfter(newEl, targetEl) {
    var parentEl = targetEl.parentNode;
    if (parentEl.lastChild == targetEl) {
        parentEl.appendChild(newEl);
    } else {
        parentEl.insertBefore(newEl, targetEl.nextSibling);
    }
}

使用:

var txtName = document.getElementById("txtName");
var htmlSpan = document.createElement("span");
htmlSpan.innerHTML = "This is a test";
insertAfter(htmlSpan, txtName);   // 作為 txtName 的兄弟節點,插在它之後

總結三要點

  1. appendChild 與 insertBefore 是原生 DOM 方法,insertAfter 只是自製函式。
  2. insertBefore 比 appendChild 靈活,可插入到子節點清單的任意位置。
  3. 使用這兩個方法插入節點的前提是:新節點與目標節點必須有共同的父節點,否則 insertBefore 會出錯誤。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved