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①

浏览器兼容性

另见