JavaScript之a(chǎn)ppendChild、insertBefore和insertAfter使用說明
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+
添加一個(gè)節(jié)點(diǎn)到指定的節(jié)點(diǎn)的子節(jié)點(diǎn)數(shù)組中,讀起來好象有點(diǎn)拗口,簡單地說就是將元素添加到指定的節(jié)點(diǎn)中
appendChild用法
target.appendChild(newChild)
newChild作為target的子節(jié)點(diǎn)插入最后的一子節(jié)點(diǎn)之后
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é)點(diǎn)前插入一個(gè)新的子節(jié)點(diǎn)
insertBefore用法
target.insertBefore(newChild,existingChild)
newChild作為target的子節(jié)點(diǎn)插入到existingChild節(jié)點(diǎn)之前
existingChild為可選項(xiàng)參數(shù),當(dāng)為null時(shí)其效果與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的應(yīng)該也有insertAfter吧?
好那我們來用Aptana編寫一個(gè)例子吧,但Aptana的智能提示告訴我其實(shí)沒有insertAfter這個(gè)方法
那么就自己定義一個(gè)羅:)
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é)點(diǎn)插入到txtName 節(jié)點(diǎn)之后
總結(jié):
1、appendChild和insertBefore是做對節(jié)點(diǎn)的方法來使用的,而insertAfter只是自定義的一個(gè)函數(shù)
2、insertBefore相對于appendChild來說,比較靈活可以將新的節(jié)點(diǎn)插入到目標(biāo)節(jié)點(diǎn)子節(jié)點(diǎn)數(shù)組中的任一位置。
3、使用appendChild和insertBefore來插入新的節(jié)點(diǎn)前提是,其兄弟節(jié)點(diǎn)必須有共同的父節(jié)點(diǎn)
相關(guān)文章
分享JavaScript監(jiān)聽全部Ajax請求事件的方法
最近在做一個(gè)小項(xiàng)目,引入了第三方j(luò)s文件,這個(gè)文件會調(diào)用XMLHttpRequest向服務(wù)器發(fā)送 Ajax請求,但是我有需要監(jiān)聽其Ajax請求的某些事件,以便額外地執(zhí)行其他腳本。于是稍微看了看監(jiān)聽 Ajax請求的事件方法,在這里分享給大家。有需要的朋友們可以參考借鑒。2016-08-08JavaScript記錄光標(biāo)在編輯器中位置的實(shí)現(xiàn)方法
這篇文章主要介紹了JavaScript記錄光標(biāo)在編輯器中位置的實(shí)現(xiàn)方法,涉及JavaScript鼠標(biāo)事件結(jié)合頁面元素的操作技巧,需要的朋友可以參考下2016-04-04JS倒計(jì)時(shí)實(shí)例_天時(shí)分秒
下面小編就為大家?guī)硪黄狫S倒計(jì)時(shí)實(shí)例_天時(shí)分秒。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-08-08JS+jQuery實(shí)現(xiàn)注冊信息的驗(yàn)證功能
本文通過實(shí)例代碼給大家分享了基于js+jquery實(shí)現(xiàn)的注冊信息驗(yàn)證功能,代碼簡單易懂,非常不錯,具有參考借鑒價(jià)值,需要的朋友參考下吧2017-09-09