JavaScript DOM——「節點層次」的注意要點

幾個概念:html

  • DOM:文檔對象模型,是針對 HTML 和 XML 文檔的一個 API(應用程序編程接口)。node

  • 根節點:就是 Document 節點。ios

  • nodeType: 全部節點的屬性,用於代表節點的類型。編程

Node 類型

DOM1 級的接口,該接口除了 IE 以外,在其餘全部瀏覽器中均可以訪問到這個類型。跨域

節點類型由在 Node 類型中定義的下列 12 個數值常量來表示,任何節點類型必居其一:瀏覽器

  1. Node.ELEMENT_NODE;安全

  2. Node.ATTRIBUTE_NODE;app

  3. Node.TEXT_NODE;dom

  4. Node.CDATA_SECTION_NODE;函數

  5. Node.ENTITY_REFERENCE_NODE;

  6. Node.ENTITY_NODE;

  7. Node.PROCESSING_INSTRUCTION_NODE;

  8. Node.COMMENT_NODE;

  9. Node.DOCUMENT_NODE;

  10. Node.DOCUMENT_TYPE_NODE;

11. Node.DOCUMENT_FRAGMENT_NODE;
12. Node.NOTATION_NODE;

分別返回 1-12 數值。

如:

<h1 id="h1">hello this is h1</h1>
<h2 id="h2">hello this is h2</h2>
<p id="p">this is a paragraph<img id="img" alt="none......"></p>

console.log(document.getElementById("h1").nodeType == Node.ELEMENT_NODE); //true

由於 IE 兼容性問題,Node 類型的構造函數無效,最好仍是將它換成數字值進行比較。如:

console.log(document.getElementById("h1").nodeType == 1); //true

nodeNamenodeValue屬性

在使用這兩個屬性以前,最好是先檢測一下節點的類型:

if (someNode.nodeValue == 1){
    value = someNode.nodeName;
}

<input id="input" type="text" name="textInput" value="this is an input">
console.log(document.getElementById("input").nodeName); //INPUT
console.log(document.getElementById("input").nodeValue); //null

對於元素節點(Node.ELEMENT_NODE),nodeName 中始終是元素的標籤名,nodeValue 中則爲 null。

節點關係

childNodes屬性和NodeList對象和它的item()方法

  • 前者中保存着一個 NodeList 對象;

  • 後者並非 Array 的實例;

  • 能夠經過方括號和 item() 方法來訪問在後者的節點;

如:

<p id="p">this is a paragraph<img id="img" alt="none......"></p>

var para = document.getElementById("p");
var array = Array.prototype.slice.call(para.childNodes,0);
console.log(array);

上述代碼在 IE8 中無效,由於 IE8 及更早版本將 NodeList 實現爲一個 COM 對象。但下面的代碼能夠在全部瀏覽器中運行:

function convertToArray(nodes){
    var array = null;
    try{
        array = Array.prototype.slice.call(nodes,0);
    }catch(ex){
        array = new Array();
        for (var i=0; i<nodes.length; i++){
            array.push(nodes[i]);
        }
    }
    return array;
}

parentNode屬性和previousSiblingnextSibling屬性

parentNode屬性指向文檔樹中的父節點;同胞節點中第一個節點的previousSibling屬性的值爲null;同理最後一個節點的nextSibling屬性的值也爲null。如:

if (someNode.nextSibling === null){
    console.log("last node in the parent's childNodes list.");
} else if(someNode.previousSibling === null){
    console.log("first node in the parent's childNodes list.");
}

firstChild屬性和lastChild屬性

這兩個屬性分別等於: someNode.childNodes[0]someNode.childNodes[someNode.childNodes.length - 1];

hasChildNodes()方法和ownerDocument屬性

前者返回是否包含子節點的布爾值;後者指向表示整個文檔的文檔節點。

<h1 id="h1">hello this is h1</h1>

var title = document.getElementById("h1");
console.log(title.childNodes) //["hello this is h1"]

<h1 id="h1">hello this is h1</h1>
var title = document.getElementById("h1");
console.log(title.ownerDocument.nodeType) //9

操做節點

如下述代碼爲例:

<p id="p">this is a paragraph<img id="img" alt="none......"></p>

appendChild()方法

該方法用於向 childNodes 列表的末尾添加一個節點。其中,若是在 調用 appendChild() 時傳入了父節點的第一個子節點,那麼該節點就會成爲父節點的最後一個子節點,如:

var txt = document.getElementById("p");
txt.appendChild(txt.firstChild);
console.log(txt.childNodes) //[<img id="img" alt="none......">, "this is a paragraph"]

insertBefore()方法

用於把節點放在 childNodes 列表中某個特定的位置上。接收兩個參數:要插入的節點和做爲參照的節點,如:

var txt = document.getElementById("p");

var newNode = document.createElement("p");
var newNode_value = document.createTextNode("hello there");
newNode.appendChild(newNode_value);

txt.insertBefore(newNode, txt.lastChild);
document.write(Array.prototype.slice.call(txt.childNodes,0));//[object Text],[object HTMLParagraphElement],[object HTMLImageElement]

若是參照節點爲 null,則 insertBefore() 與 appendChild() 執行相同的操做。

replaceChild()方法

該方法接收兩個參數:要插入的節點和要替換的節點,如:

var txt = document.getElementById("p");

var newNode = document.createElement("p");
var newNode_value = document.createTextNode("hello there");
newNode.appendChild(newNode_value);

txt.replaceChild(newNode, txt.lastChild);
document.write(Array.prototype.slice.call(txt.childNodes,0));//[object Text],[object HTMLParagraphElement]

removeChild()方法

該方法接收一個參數:要刪除的節點,如:

var txt = document.getElementById("p");

txt.removeChild(txt.lastChild);
document.write(Array.prototype.slice.call(txt.childNodes,0));//[object Text]

其餘方法

cloneNode()方法

該方法全部類型節點都具備;用於建立調用這個方法的節點的一個徹底相同的副本。接收一個參數,表示是否執行深賦值。true 執行深複製,複製節點及整個子節點樹;false 執行淺複製,只複製節點自己,後要經過 appendChild() 等方法添加到文檔中。如:

<ul id="unordered">
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
</ul>

var myList = document.getElementById("unordered");
var deepList = myList.cloneNode(true);
console.log(deepList.childNodes.length); //7 (IE < 9 版本狀況下爲3,由於不會建立空白符節點。)

var shallowList = myList.cloneNode(false);
console.log(shallowList.childNodes.length); //0

normalize()方法

該方法的做用是處理文檔樹中的文本節點。在出現文本節點不包含文本,或者鏈接出現兩個文本節點的狀況下,就刪除它。

Document 類型

JavaScript 經過 Document 類型表示文檔,在瀏覽器中,document 對象是 HTMLDocument 的一個實例,表示整個 HTML 頁面。Document 節點具備如下特徵:

  1. console.log(document.nodeType + document.nodeName + document.nodeValue + document.parentNode + document.ownerDocument); //9#documentnullnullnull

  2. 以及其子節點多是一個 DocumentType(最多一個)、Element(最多一個)、ProcessingInstruction 或 Comment。

文檔的子節點

documentElement屬性和body屬性

其子節點多是一個 DocumentType(最多一個)、Element(最多一個)、ProcessingInstruction 或 Comment。但還有兩個內置的訪問其子節點的方式:一個是 documentElement 屬性,該屬性始終指向 <html> 元素如:

var html = document.getElementsByTagName("html")[0];
console.log(document.documentElement === html); //true

var html = document.firstChild;
console.log(document.documentElement === html); //true

var html = document.childNodes[0];
console.log(document.documentElement === html); //true

以上代碼創建在以下網頁源代碼之上:

<html>
    <head>
    </head>
    <body>
    <script>
        var html = document.childNodes[0];
        console.log(document.documentElement === html); //true
    
    </script>
    </body>
</html>

另一個則是 body 屬性。直接指向 <body> 元素。

DocumentTypedoctype屬性

一般將 <!DOCTYPE> 標籤當作一個與文檔其餘部分不一樣的實體,能夠經過 doctype 屬性(document.doctype)查看。如:

<!doctype html>
<html>
    <head>
    </head>
    <body>
    <script>
        console.log(document.doctype); //<!DOCTYPE html>    
    </script>
    </body>
</html>

瀏覽器對 document.doctype 的支持差異很大,主要有:

  • IE8 及以前的版本:當作註釋,document.doctype 的值爲 null;

  • IE9+ 及 Firefox:做爲第一個子節點;

  • Safari、Chrome 和 Opera:不做爲文檔的子節點。

另外,按理說出如今 html 標籤以外的註釋也算是文檔的子節點。如:

<!--第一個註釋-->
<html>
    <head>
    </head>
    <body>
    </body>
</html>
<!--第二個註釋-->

瀏覽器在處理位於 html 標籤以外的註釋方面存在以下差別:

  • IE8 及以前的版本、Safari 3.1 及更高的版本、Opera 和 Chrome 只爲第一條註釋建立節點;

  • IE9 及更高的版本將兩個註釋都建立爲節點;

  • Firefox、Safari 3.1 以前的版本會忽略這兩個註釋。

文檔信息

title屬性

document 對象的另外一個屬性是 title,包含這 title 元素中的文本,可是修改 title 屬性的值並不會
改變 title 標籤元素。如:

var x = setTimeout(setTitle, 1000);
function setTitle(){
    document.title = "Hello";
    var y = setTimeout(setTitle2, 1000);
    function setTitle2(){
        document.title = "World";
        x = setTimeout(setTitle, 1000);
    }
}

以上代碼能夠以1秒的速度自動切換顯示 title 標籤的內容

URLdomainreferrer屬性

三者分別包含完整的 URL;頁面的域名以及鏈接到當前頁面的那個頁面的 URL。三個屬性當中只有 domain 是能夠設置的。如:

//假設頁面來自 p2p.wrox.com 域

document.domain = "wrox.com"; //成功
document.domain = "baidu.com"; //失敗

另外,因爲跨域安全限制,來自不一樣的子域的頁面沒法經過 js 通訊。還有,若是域名一開始是「鬆散的」(loose),那麼就不能再設置爲「緊繃的」(tight)。即將 document.domain 設置爲"wrox.com"以後,就不能再將其設置回"p2p.wrox.com"不然將出錯。

查找元素

getElementById()方法

該方法接收一個參數即元素的 ID。如下面的元素爲例:

<div id="myDiv">Some text</div>

可使用下面的代碼取得這個元素:

var div = document.getElementById("myDiv");
var div = document.getElementById("mydiv"); //無效的ID 可是能夠在 IE7 及更早的版本中使用

若是文檔中出現多個 ID 相同的元素,則取得第一次出現的那個。

IE7 及更早的版本在 name 特性與給定的 ID 匹配的表單元素(input textarea button select)也會被該方法訪問。如:

<input type="text" name="myElement" value="hello">
<div id="myElement">Some text</div>

console.log(document.getElementById("myElement"));

因此最好不要把 id 與 name 設置成同一個名稱。

getElementsByTagName()方法、HTMLCollection屬性以及namedItem()方法

前者接收一個參數即要去的的元素的標籤名,後者則是該方法返回的對象,以下代碼將取得全部 img 元素,並返回一個 HTMLCollection 對象:

<img src="" alt="">
<img src="" alt="">
<img src="" alt="">
<img src="" alt="">

console.log(document.getElementsByTagName("img").length); //4

這裏返回的 HTMLCollection 對象能夠經過方括號語法或 item() 方法來訪問:

<body>
    <img src="" alt="">
    <img src="pics/topics.png" height="104" width="410" alt="">
    <img src="" alt="">
    <img src="" alt="">
    <script>
    var images = document.getElementsByTagName("img");
    console.log(images.length);
    console.log(images[1].src); //獲取src
    console.log(images.item(1).src); //獲取src
    </script>
</body>

另外,能夠經過namedItem()方法來得到指定的 name 特性的項如:

<body>
    <img src="" alt="">
    <img src="pics/topics.png" height="104" width="410" alt="" name="secImg">
    <script>
    var images = document.getElementsByTagName("img");
    console.log(images.namedItem("secImg").src); //獲取了name特性爲secImg的img標籤的src
    </script>
</body>

固然也可使用方括號語法:

<body>
    <img src="" alt="">
    <img src="pics/topics.png" height="104" width="410" alt="" name="secImg">
    <script>
    var images = document.getElementsByTagName("img");
    console.log(images.namedItem("secImg").src); //獲取了name特性爲secImg的img標籤的src
    console.log(images["secImg"].src); //與上面的相同
    </script>
</body>

在後臺,對數值索引就會調用 item(),而對字符串索引就會調用 namedItem()。

另外,能夠向 getElementsByTagName() 中傳入「*」。表示所有標籤;

getElementsByName()方法

該方法返回給定 name 特性的全部元素。最經常使用的狀況是取得單選按鈕。

<body>
    <fieldset>
        <legent>Which color do you perfer?</legent>
        <ul>
            <li>
                <input type="radio" name="color" value="red" id="colorRed">
                <label for="">Red</label>
            </li>
            <li>
                <input type="radio" name="color" value="green" id="colorGreen">
                <label for="">Green</label>
            </li>
            <li>
                <input type="radio" name="color" value="blue" id="colorBlue">
                <label for="">Blue</label>
            </li>
        </ul>
    </fieldset>
    <script>
        var radios = document.getElementsByName("color");
        console.log(radios[2].value); //blue
    </script>
</body>

在這裏 namedItem() 方法只會取得第一項,由於每一項的 name 特性都是 color。

特殊集合(.anchors/.forms/.images/.links)

  • document.anchors:文檔中全部帶 name 特性的 a 元素;

  • document.applets:文檔中的全部 applet 元素。已經不推薦使用 applet 元素了。

  • document.forms:文檔中全部 form 元素

  • document.images:文檔中全部 img 元素

  • document.links:文檔中全部帶 href 特性的 a 元素;

以下:

<form action=""></form>
<form action=""></form>
<img src="" alt="">
<a href="#">abc</a>
<a name="noName" href="#">abc</a>
<a name="noName" href="#">abc</a>

console.log(document.anchors.length); //2
console.log(document.forms.length); //2
console.log(document.links.length); //3

DOM 一致性檢測

document.implementation屬性與hasFeature()方法

因爲 DOM 有多個級別,包含多個部分,所以檢測瀏覽器實現了 DOM 的哪些部分是非必要。該方法接收兩個參數:要檢測的 DOM 功能的名稱及版本號。若是瀏覽器支持,則返回 true,如:

console.log(document.implementation.hasFeature("XML", "1.0")); //True

列表以下:

Core    實現 Node、Element、Document、Text 和其餘全部DOM實現都要求實現的基本接口 全部遵照 DOM 標準的實現都必須支持該模塊。

HTML    實現 HTMLElement、HTMLDocument 和其餘 HTML 專有接口。

XML 實現 Entity、EntityReference、ProcessingInstruction、Notation 和其餘 XML 文檔專用的節點類型。

StyleSheets 實現描述普通樣式表的簡單接口。

CSS 實現 CSS 樣式表專有的接口。

CSS2    實現 CSS2Properties 接口。

Events  實現基本的事件處理接口。

UIEvents    實現處理用戶界面事件的接口。

MouseEvents 實現處理鼠標事件的接口。

HTMLEvents  實現處理 HTML 事件的接口。

MutationEvents  實現處理文檔變化事件的接口。

Range   實現操做文檔範圍的接口。

Traversal   實現進行高級文檔遍歷的接口。

Views   實現處理文檔視圖的接口。

文檔寫入

write()writeln()open()以及close()

其中,writeln() 會在字符串最後添加一個換行符(\n)如:

document.write("hello");
document.writeln("there"); //最後面有個換行符
document.write("anybodyHome?");
//hellothere anybodyHome?

此外,還可使用 write() 和 writeln() 方法動態地包含外部資源。

須要注意的是,若是在文檔加載完畢後再執行 document.write 則會重寫文檔。

方法 open() 和 close() 分別用於打開和關閉網頁的輸出流。

Element 類型

該類型用於表現 XML 或 HTML 元素,提供了對元素標籤名、子節點及特性的訪問。主要特性以下:

var x = document.getElementsByTagName("p")[0];
console.log(x.tagName); //P
console.log(x.nodeName); //P
console.log(x.nodeType); //1
console.log(x.nodeValue); //null
console.log(x.parentNode); //HTMLDivElement

其子節點多是 Element、Text、Comment、ProcessingInstruction、CDATASection 或 EntityReference。

由於 XML 和 HTML 的標籤名大小寫關係,在比較標籤名的時候最好先轉換成小寫,如:

var x = document.getElementsByTagName("p")[0];
if (x.tagName === "p") {
    console.log('testing1');
};
if (x.tagName.toLowerCase() === "p") {
    console.log('testing2');
};
//testing2

HTML元素

全部 HTML 元素都由 HTMLElement 類型表示,標準特性以下:

  • id:元素的惟一標識符;

  • title:附加說明信息;

  • lang:語言代碼;

  • dir:語言方向;

  • className:元素的 class 特性對應,即 CSS 類。

如:

<div id="bd" class="myDiv" title="Body text" lang="en" dir="ltr"></div>

var div = document.getElementById("bd");
console.log(bd.dir); //ltr

另外還有其餘衆多 HTML 元素以及與之關聯的類型。這裏再也不累述。

取得特性

getAttribute()方法

該方法主要是取得特性的值;

須要注意的是,任何元素的全部特性,均可以經過 DOM 元素自己的屬性來訪問。可是自定義的特性不會以屬性的形式添加到 DOM 對象中。如:

<div id="bd" my="hello" class="myDiv" title="Body text" lang="en" dir="ltr"></div>
<script>
var div = document.getElementById("bd");
console.log(div.my); //undefined(IE 除外)
</script>

因爲各類緣由,應該只有在取得自定義特性值的狀況下,纔會使用該方法,如:

<div id="bd" my="hello" class="myDiv" title="Body text" lang="en" dir="ltr"></div>
<script>
var div = document.getElementById("bd");
console.log(div.my); //undefined(IE 除外)
console.log(div.getAttribute("my")); //應該用getAttribute方法訪問自定義特性
</script>

另外須要注意的是,根據 HTML5 規範,自定義特性應該加上 data- 前綴以便驗證,如:

<div id="bd" class="myDiv" title="Body text" lang="en" dir="ltr"></div>
<script>
var div = document.getElementById("bd");
div.setAttribute("data-my_attr", "value");
console.log(div.getAttribute("data-my_attr")); //value
console.log(div.attributes[5].name); //data-my_attr
</script>

設置特性

setAttribute()方法

該方法接收兩個參數:要設置的特性名和值。若是特性名存在,則執行替換操做。如:

<div id="bd" class="myDiv" title="Body text" lang="en" dir="ltr"></div>
<script>
var div = document.getElementById("bd");
div.my = "hello";
console.log(div.getAttribute("my")); //null
console.log(div.my); //hello
</script>

綜上所述,在取得特性值的狀況下,最好用getAttribute()方法取得自定義特性,用 DOM 屬性訪問公認的特性;在設置特性值的狀況下,最好用 DOM 屬性來設置公認的特性,用setAttribute()方法設置自定義特性。如:

<div id="bd" class="myDiv" title="Body text" lang="en" dir="ltr"></div>
<script>
var div = document.getElementById("bd");

div.my = "value1";
console.log(div.my); //value1
console.log(div.getAttribute("my")); //null

div.setAttribute("my2", "value2");
console.log(div.my2); //undefined
console.log(div.getAttribute("my2")); //value2
</script>

總之,最好直接經過屬性來讀取和設置特性。

removeAttribute()方法

一個參數,IE6 及之前的版本不支持該方法。如:

<div id="bd" class="myDiv" title="Body text" lang="en" dir="ltr"></div>
<script>
var div = document.getElementById("bd");

div.my = "hello";
console.log(div.my);

div.removeAttribute("my");
console.log(div.my);

div.setAttribute("my2", "value");
console.log(div.getAttribute("my2"));

div.removeAttribute("my2");
console.log(div.getAttribute("my2")); //null
</script>

attributes 屬性

該屬性包含一個 NamedNodeMap 對象,該對象有下列方法(不經常使用):

  • getNamedItem(Name):返回 nodeName 屬性等於 Name 的節點;

  • removeNamedItem(Name):移除指定的節點;

  • setNamedItem(Node):添加指定的節點;

  • item(pos):返回位於數字 pos 位置的節點;

具體以下:

<div id="divId">
    <p id="pId">hhh</p>
</div>

var pId = document.getElementById("pId");
var namedItem = pId.attributes.getNamedItem("id").nodeValue;
console.log(namedItem); //pId
var attrList = pId.attributes.item(0).nodeValue; //pId
console.log(attrList);
pId.attributes.removeNamedItem("id");
console.log(pId.id); //

該屬性常常涌來遍歷元素的特性,如:

<p id="pId" name="para">hhh</p>

var pElem = document.getElementById("pId");

function outputAttributes(element) {
    var pairs = new Array();
    var attrName, attrValue, i, len;
    for (i = 0, len = element.attributes.length; i < len; i++) {
        attrName = element.attributes[i].nodeName;
        attrValue = element.attributes[i].nodeValue;
        pairs.push(attrName + "=\"" + attrValue + "\"");
    }
    return pairs.join(" ");
}
console.log(outputAttributes(pElem)); //id="pId" name="para"

可是須要強調的是:

  • 不通瀏覽器返回的順序不通;

  • IE7 及更早的版本會返回 HTML 元素中全部可能的特性,包括沒有指定的特性

每一個特性節點都有一個名爲 specified 的屬性,這個屬性的值若是爲 true,則意味着要麼是在 HTML 中制定了相應特性,要麼是經過 setAttribute() 方法設置了該特性。

上面的代碼兼容性考慮,應該改成下面這樣:

<p id="pId" name="para">hhh</p>

var pElem = document.getElementById("pId");

function outputAttributes(element) {
    var pairs = new Array();
    var attrName, attrValue, i, len;
    for (i = 0, len = element.attributes.length; i < len; i++) {
        attrName = element.attributes[i].nodeName;
        attrValue = element.attributes[i].nodeValue;
        if (element.attributes[i].specified) {
            pairs.push(attrName + "=\"" + attrValue + "\"");
        };
    }
    return pairs.join(" ");
}
console.log(outputAttributes(pElem)); //id="pId" name="para"

建立元素

createElement()方法

該方法接收一個參數,即要建立元素的標籤名。用該方法建立的新元素被賦予了ownerDocument屬性。隨後經過appendChild()等方法添加到文檔樹中。如:

var newElementP = document.createElement("p");
var newElementPValue = document.createTextNode("data");
newElementP.title = "im title";
newElementP.appendChild(newElementPValue);
document.body.appendChild(newElementP);
console.log(newElementP.lastChild.nodeValue); //data
console.log(newElementP.title); //im title

在 IE 中能夠用另外一種方式使用 createElement(),即爲這個方法傳入完整的元素標籤,也能夠包含屬性,但這種方法存在不少問題,不建議使用。(具體見《js高級程序設計》第十章節點層次 Element 類型)

元素的子節點

如下面代碼爲例:

<ul id="ulList">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>

var list = document.getElementById("ulList");
var childNodesList = list.childNodes;
console.log(childNodesList.length); //7

for (var i = childNodesList.length - 1; i >= 0; i--) {
    if (childNodesList[i].nodeType == 1) {
        console.log(childNodesList[i].nodeName); //LI*3
    };
};
for (var i = childNodesList.length - 1; i >= 0; i--) {
    if (childNodesList[i].nodeType == 3) {
        document.write(childNodesList[i].nodeValue); //LI*3的text節點值一、二、3
    };
};

如同上面的代碼同樣,若是須要經過 childNodes 屬性遍歷子節點,呢麼必定要在操做之前檢查 nodeType 屬性。由於不一樣的瀏覽器會返回不一樣的節點個數:

<ul id="ulList"><li>1</li><li>2</li><li>3</li></ul>

這裏纔會返回 childNodesList.length 爲3。

若是要返回上面代碼中的全部 li 元素,可使用以下代碼:

var ulList = document.getElementById("ulList");
var liList = ulList.getElementsByTagName("li");
console.log(liList.length); //3

Text 類型

要注意的是,字符串會通過 HTML 或 XML 編碼。如:

var pElem = document.getElementById("pId");
pElem.firstChild.nodeValue = "<p>hello there</p>";
console.log(pElem.innerHTML); //&lt;p&gt;hello there&lt;/p&gt

建立文本節點

createTextNode()方法

該方法建立文本節點,接收一個參數即文本字符串。按理說一個元素只有一個文本節點,可是若是爲其賦予了多個節點,那麼這些節點中的文本就會連起來,而且中間沒有空格。如:

var newP = document.createElement("p");
var newPValue = document.createTextNode("data");
newP.appendChild(newPValue);
document.body.appendChild(newP);
var anotherPValue = document.createTextNode("anotherData");
newP.appendChild(anotherPValue); //dataanotherData

規範化文本節點

normalize()方法

該方法在一個包含兩個或多個文本節點的父元素上調用,將會把全部文本節點合成成一個節點。如:

var newP = document.createElement("p");
var newPValue = document.createTextNode("data");
newP.appendChild(newPValue);
document.body.appendChild(newP);
var anotherPValue = document.createTextNode("anotherData");
newP.appendChild(anotherPValue); //dataanotherData
console.log(newP.childNodes.length); //2
newP.normalize();
console.log(newP.childNodes.length); //1

分割文本節點

splitText()方法

這個方法將一個文本節點分紅兩個文本節點,原來的文本節點包含從開始到指定位置以前的內容;新的文本節點將包含剩下的文本。這個方法會返回一個新文本節點。如:

var newP = document.createElement("p");
var newPValue = document.createTextNode("data");
newP.appendChild(newPValue);
document.body.appendChild(newP);
var anotherPValue = document.createTextNode("anotherData");
newP.appendChild(anotherPValue); //dataanotherData

newP.normalize();
var anotherNewP = newP.firstChild.splitText(4);
console.log(newP.firstChild.nodeValue); //data
console.log(newP.lastChild.nodeValue); //anotherData

newP.normalize();
console.log(newP.firstChild.nodeValue); //dataanotherData

Comment 類型

createComment()方法

該方法能夠建立註釋節點。不過鮮有人使用。擁有除 splitText() 以外的全部字符串操做方法。

CDATASection 類型

該類型只有在真正的 XML 文檔中可使用如下方法,瀏覽器會解釋他爲 Comment 類型:

<div id="myDiv">
    <![CDATA[This is some content.]]>
</div>

console.log(document.getElementById("myDiv").firstChild); //Comment

createCDataSection()方法

該方法用來建立 CDATA 區域,只需爲其傳入節點的內容便可

DocumentType 類型

不經常使用。包含着與文檔的 doctype 有關的全部信息。

該類型對象的三個屬性:name、entities 和 notations。其中,name 表示文檔類型的名稱;entities 是由文檔類型描述的實體的 NamedNodeMap 對象;notations 是由文檔類型描述的符號的 NamedNodeMap 對象。通常來講只有 name 有點用。

console.log(document.doctype.name); //html

IE 不支持。

DocumentFragment 類型

createDocumentFragment()方法

主要做用就是用來避免經過逐個添加元素所致使的瀏覽器反覆渲染新信息的問題,使用一個文檔片斷來保存建立的元素,而後再一次性將它們添加到文檔中。如:

<ul id="myList"></ul>

var fragment = document.createDocumentFragment();
var ul = document.getElementById("myList");
var li = null;

for (var i = 0; i < 3; i++) {
    li = document.createElement("li");
    li.appendChild(document.createTextNode("Item" + (i + 1)));
    fragment.appendChild(li);
};

ul.appendChild(fragment);

Attr 類型

該對象又3個屬性:name、value 和 specified。但使用getAttribute()setAttribute()removeAttribute()方法更好用。

相關文章
相關標籤/搜索