1. 程式人生 > >常見dom樹操作

常見dom樹操作

js操作dom節點

1.訪問節點

document.getElementById(id);返回對擁有指定id的第一個物件進行訪問document.getElementsByName(name);返回帶有指定名稱的節點集合注意:Elementsdocument.getElementsByTagName(tagname);
返回帶有指定標籤名的物件集合
注意:Elements

document.getElementsByClassName(classname);
返回帶有指定class名稱的物件集合
注意:Elements

2.生成節點

document.createElement(eName);建立一個節點

document.createAttribute(attrName);對某個節點建立屬性document.createTextNode(text);建立文字節點

3.新增節點
document.insertBefore(newNode,referenceChild);
在某個節點前插入節點

parentNode.appendChild(newNode);
給某個節點新增子節點

4.複製節點
cloneNode(true | false);
複製某個節點
引數:是否複製原節點的所有屬性

5.刪除節點
parentNode.removeChild(node)
刪除某個節點的子節點
node是要刪除的節點
注意:

IE會忽略節點間生成的空白文字節點(例如,換行符號),而Mozilla不會這樣做。在刪除指定節點的時候不會出錯,但是如果要刪除最後一個子結點或者是第一個子結點的時候,就會出現問題。這時候,就需要用一個函式來判斷首個子結點的節點型別。
元素節點的節點型別是 1,因此如果首個子節點不是一個元素節點,它就會移至下一個節點,然後繼續檢查此節點是否為元素節點。整個過程會一直持續到首個元素子節點被找到為止。通過這個方法,我們就可以在 Internet Explorer Mozilla 得到正確的方法。

6.修改文字節點
appendData(data);
data加到文字節點後面

deleteData(start,length);
將從

start處刪除length個字元

insertData(start,data)
start處插入字元,start的開始值是0;

replaceData(start,length,data)
start處用data替換length個字元

splitData(offset)
offset處分割文字節點

substringData(start,length)
start處提取length個字元

7.屬性操作
getAttribute(name)
通過屬性名稱獲取某個節點屬性的值

setAttribute(name,value);
修改某個節點屬性的值

removeAttribute(name)
刪除某個屬性

<html>< head>   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />   <title>HTML DOM</title>   <script type=text/javascript>   function   Load_message()   {    var oimg=document.getElementById("a");       alert(oimg.getAttribute("border"));    oimg.setAttribute("alt","DOM Test");   }   </script>< /head>< body onload="Load_message();">   <img border="0" width="100" height="150" id="a"/>< /body>< /html>8.查詢節點parentObj.firstChild如果節點為已知節點的第一個子節點就可以使用這個方法。此方法可以遞迴進行使用parentObj.firstChild.firstChild.....parentObj.lastChild獲得一個節點的最後一個節點,與firstChild一樣也可以進行遞迴使用parentObj.lastChild.lastChild.....parentObj.childNodes獲得節點的所有子節點,然後通過迴圈和索引找到目標節點9.獲取相鄰的節點neborNode.previousSibling :獲取已知節點的相鄰的上一個節點nerbourNode.nextSlbling: 獲取已知節點的下一個節點10.獲取父節點childNode.parentNode:得到已知節點的父節點

11替換節點 方法replace(new,old)

<html>< head>      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />      <title>HTML DOM</title><script type=text/javascript>      function replaceMessage()      {       var oNewp=document.createElement("p");       var oText=document.createTextNode("World Hello");       oNewp.appendChild(oText);       var oOldp=document.body.getElementsByTagName("p")[0];       oOldp.parentNode.replaceChild(oNewp,oOldp);      }      </script>< /head>< body onload="replaceMessage();">      <p>hello world!</p>< /body>< /html>