DOM
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
- : 字符串
"#text"。
- : 字符串
示例
本示例会显示若干节点的节点名称。
这是一些 HTML:
<div id="d1">你好,世界</div>
文本<span>文本</span>文本<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">尚未计算。</output>
以及以下脚本:
let node = document.querySelector("body").firstChild;
let result = "节点名称如下:\n";
while (node) {
result += `${node.nodeName}\n`;
node = node.nextSibling;
}
const output = document.getElementById("result");
output.innerText = result;
示例
规范
浏览器兼容性
参见
- Element.tagName
- Attr.name
- DocumentType.name
- ProcessingInstruction.target
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
