Node: nodeName 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Node 的只讀 nodeName 屬性返回當前節點的名稱,型別為字串。

字串。不同型別節點的取值如下:

Attr

Attr.name 的值,即屬性的限定名稱

CDATASection

字串 "#cdata-section"

Comment

字串 "#comment"

Document

字串 "#document"

DocumentFragment

字串 "#document-fragment"

DocumentType

DocumentType.name 的值

Element

Element.tagName 的值,如果是 HTML 元素,則為該元素標籤的大寫名稱;如果是 XML 元素(如 SVG 或 MathML 元素),則為該元素標籤的小寫名稱。

ProcessingInstruction

ProcessingInstruction.target 的值

文字

字串 "#text"

示例

本示例顯示了幾個節點的節點名稱。

html
This is some HTML:
<div id="d1">Hello world</div>
<!-- Example of comment -->
Text <span>Text</span> Text<br />
<svg height="20" width="20">
  <circle cx="10" cy="10" r="5" stroke="black" stroke-width="1" fill="red" />
</svg>
<hr />
<output id="result">Not calculated yet.</output>

以及以下指令碼:

js
let node = document.querySelector("body").firstChild;
let result = "Node names are:\n";
while (node) {
  result += `${node.nodeName}\n`;
  node = node.nextSibling;
}

const output = document.getElementById("result");
output.innerText = result;

規範

規範
DOM
# ref-for-dom-node-nodename①

瀏覽器相容性

另見