js中AppendChild與insertBefore的用法詳細解析
appendChild定義
appendChild(newChild: Node) : Node
Appends a node to the childNodes array for the node.
Supported: IE 5.0+, Mozilla 1.0+, Netscape 6.0+, Safari 1.0+, Opera 7.0+
添加一個節(jié)點到指定的節(jié)點的子節(jié)點數(shù)組中,讀起來好象有點拗口,簡單地說就是將元素添加到指定的節(jié)點中
appendChild用法
target.appendChild(newChild)
newChild作為target的子節(jié)點插入最后的一子節(jié)點之后
appendChild例子
var newElement = document.Document.createElement('label');
newElement.Element.setAttribute('value', 'Username:');
var usernameText = document.Document.getElementById('username');
usernameText.appendChild(newElement);
insertBefore定義
The insertBefore() method inserts a new child node before an existing child node.
insertBefore() 方法的作用是:在現(xiàn)有的子節(jié)點前插入一個新的子節(jié)點
insertBefore用法
target.insertBefore(newChild,existingChild)
newChild作為target的子節(jié)點插入到existingChild節(jié)點之前
existingChild為可選項參數(shù),當為null時其效果與appendChild一樣
insertBefore例子
var oTest = document.getElementById("test");
var newNode = document.createElement("p");
newNode.innerHTML = "This is a test";
oTest.insertBefore(newNode,oTest.childNodes[0]);
好了那么有insertBefore的應該也有insertAfter吧?
好那我們來用Aptana編寫一個例子吧,但Aptana的智能提示告訴我其實沒有insertAfter這個方法
那么就自己定義一個羅:)
insertAfter定義
function insertAfter(newEl, targetEl)
{
var parentEl = targetEl.parentNode;
if(parentEl.lastChild == targetEl)
{
parentEl.appendChild(newEl);
}else
{
parentEl.insertBefore(newEl,targetEl.nextSibling);
}
}
insertAfter用法與例子
var txtName = document.getElementById("txtName");
var htmlSpan = document.createElement("span");
htmlSpan.innerHTML = "This is a test";
insertAfter(htmlSpan,txtName);
將htmlSpan 作為txtName 的兄弟節(jié)點插入到txtName 節(jié)點之后
總結(jié):
1、appendChild和insertBefore是做對節(jié)點的方法來使用的,而insertAfter只是自定義的一個函數(shù)
2、insertBefore相對于appendChild來說,比較靈活可以將新的節(jié)點插入到目標節(jié)點子節(jié)點數(shù)組中的任一位置。
3、使用appendChild和insertBefore來插入新的節(jié)點前提是,其兄弟節(jié)點必須有共同的父節(jié)點
相關(guān)文章
js實現(xiàn)仿Windows風格選項卡和按鈕效果實例
這篇文章主要介紹了js實現(xiàn)仿Windows風格選項卡和按鈕效果的方法,可實現(xiàn)類似windows選項卡風格的tab標簽效果,需要的朋友可以參考下2015-05-05Apply an AutoFormat to an Excel Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet...2007-06-06JavaScript canvas動畫實現(xiàn)時鐘效果
這篇文章主要為大家詳細介紹了JavaScript canvas動畫實現(xiàn)時鐘效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-02-02javascript實現(xiàn)十六進制顏色值(HEX)和RGB格式相互轉(zhuǎn)換
這篇文章主要介紹了javascript實現(xiàn)十六進制顏色值(HEX)和RGB格式之間的轉(zhuǎn)換,使用正則的方法實現(xiàn)RGB顏色轉(zhuǎn)換為16進制,需要的朋友可以參考下2014-06-06