HTML DOM Element nodeType 屬性

定義和用法

nodeType 屬性以數字形式返回指定節點的節點類型。

  • 如果節點是元素節點,則 nodeType 屬性將返回 1
  • 如果節點是屬性節點,則 nodeType 屬性將返回 2
  • 如果節點是文本節點,則 nodeType 屬性將返回 3
  • 如果節點是注釋節點,則 nodeType 屬性將返回 8

該屬性是只讀的。

另請參閱:

nodeName 屬性

nodeValue 屬性

tagName 屬性

childNodes 屬性

實例

例子 1

獲取 body 元素的節點類型:

var x = document.getElementById("myP").nodeType;

親自試一試

例子 2

返回 <body> 元素的節點類型:

document.body.nodeType;

親自試一試

例子 3

顯示所有元素的節點類型:

const nodes = document.body.childNodes;
let text = "";
for (let i = 0; i < nodes.length; i++) {
  text += nodes[i].nodeType + "<br>";
}

親自試一試

例子 4

獲取 "myDIV" 的第一個子節點的節點名稱、值和類型:

const x = document.getElementById("myDIV").firstChild;
let text = "";
text += "Name: " + x.nodeName + "<br>";
text += "Value: " + x.nodeValue + "<br>";
text += "Type: " + x.nodeType;

親自試一試

語法

node.nodeType

返回值

類型 描述
數值 節點的節點類型。請見下表。

節點類型

HTML 或 XML 文檔的文檔、元素、屬性以及其他節點擁有不同的節點類型。

有 12 種不同的節點類型,它們可能有各種節點類型的子節點:

類型 描述 子節點
1 Element 表示元素
  • Element
  • Text
  • Comment
  • ProcessingInstruction
  • CDATASection
  • EntityReference
2 Attr 表示屬性
  • Text
  • EntityReference
3 Text 表示元素或屬性中的文本內容 無。
4 CDATASection 表示文檔中的 CDATA 部分
(不會被解析器解析的文本)
無。
5 EntityReference 表示實體引用
  • Element
  • ProcessingInstruction
  • Comment
  • Text
  • CDATASection
  • EntityReference
6 Entity 表示實體
  • Element
  • ProcessingInstruction
  • Comment
  • Text
  • CDATASection
  • EntityReference
7 ProcessingInstruction 表示處理指令 無。
8 Comment 表示注釋 無。
9 Document 表示整個文檔(DOM 樹的根節點)
  • Element
  • ProcessingInstruction
  • Comment
  • DocumentType
10 DocumentType 向為文檔定義的實體提供接口 無。
11 DocumentFragment 表示“輕量級”的 Document 對象,它可保存文檔的片段。
  • Element
  • ProcessingInstruction
  • Comment
  • Text
  • CDATASection
  • EntityReference
12 Notation 表示在 DTD 中聲明的符號 無。

節點類型 - 返回值

每種節點類型的 nodeName 和 nodeValue 屬性的返回值:

類型 nodeName nodeValue
1 Element 元素名 null
2 Attr 屬性名 屬性值
3 Text #text 節點的內容
4 CDATASection #cdata-section 節點的內容
5 EntityReference 實體引用的名稱 null
6 Entity 實體名稱 null
7 ProcessingInstruction target 節點的內容
8 Comment #comment 注釋文本
9 Document #document null
10 DocumentType doctype 名稱 null
11 DocumentFragment #document 片段 null
12 Notation 符號名稱 null

節點類型 - 命名常量

類型 命名常量
1 ELEMENT_NODE
2 ATTRIBUTE_NODE
3 TEXT_NODE
4 CDATA_SECTION_NODE
5 ENTITY_REFERENCE_NODE
6 ENTITY_NODE
7 PROCESSING_INSTRUCTION_NODE
8 COMMENT_NODE
9 DOCUMENT_NODE
10 DOCUMENT_TYPE_NODE
11 DOCUMENT_FRAGMENT_NODE
12 NOTATION_NODE

瀏覽器支持

element.nodeType 是 DOM Level 1 (1998) 特性。

所有瀏覽器都完全支持它:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
支持 9-11 支持 支持 支持 支持