Node.nodeType - Web APIs 编辑

The read-only Node.nodeType property is an integer that identifies what the node is. It distinguishes different kind of nodes from each other, such as elements, text and comments.

Syntax

var type = node.nodeType;

Returns an integer which specifies the type of the node. Possible values are listed in Node type constants.

Constants

Node type constants

ConstantValueDescription
Node.ELEMENT_NODE1An Element node like <p> or <div>.
Node.ATTRIBUTE_NODE2An Attribute of an Element.
Node.TEXT_NODE3The actual Text inside an Element or Attr.
Node.CDATA_SECTION_NODE4A CDATASection, such as <!CDATA[[ … ]]>.
Node.PROCESSING_INSTRUCTION_NODE7A ProcessingInstruction of an XML document, such as <?xml-stylesheet … ?>.
Node.COMMENT_NODE8A Comment node, such as <!-- … -->.
Node.DOCUMENT_NODE9A Document node.
Node.DOCUMENT_TYPE_NODE10A DocumentType node, such as <!DOCTYPE html>.
Node.DOCUMENT_FRAGMENT_NODE11A DocumentFragment node.

Deprecated node type constants This deprecated API should no longer be used, but will probably still work.

The following constants have been deprecated and should not be used anymore.

ConstantValueDescription
Node.ENTITY_REFERENCE_NODE5An XML Entity Reference node, such as &foo;. Removed in DOM4.
Node.ENTITY_NODE6An XML <!ENTITY …> node. Removed in DOM4.
Node.NOTATION_NODE12An XML <!NOTATION …> node. Removed in DOM4.

Examples

Different types of nodes

document.nodeType === Node.DOCUMENT_NODE; // true
document.doctype.nodeType === Node.DOCUMENT_TYPE_NODE; // true

document.createDocumentFragment().nodeType === Node.DOCUMENT_FRAGMENT_NODE; // true

var p = document.createElement("p");
p.textContent = "Once upon a time…";

p.nodeType === Node.ELEMENT_NODE; // true
p.firstChild.nodeType === Node.TEXT_NODE; // true

Comments

This example checks if the first node inside the document element is a comment, and displays a message if not.

var node = document.documentElement.firstChild;
if (node.nodeType !== Node.COMMENT_NODE) {
  console.warn("You should comment your code!");
}

Specifications

SpecificationStatusComment
DOM
The definition of 'Node.nodeType' in that specification.
Living StandardDeprecated ATTRIBUTE_NODE, ENTITY_REFERENCE_NODE and NOTATION_NODE types.
Document Object Model (DOM) Level 3 Core Specification
The definition of 'Node.nodeType' in that specification.
ObsoleteNo changes.
Document Object Model (DOM) Level 2 Core Specification
The definition of 'Node.nodeType' in that specification.
ObsoleteNo changes.
Document Object Model (DOM) Level 1 Specification
The definition of 'Node.nodeType' in that specification.
ObsoleteInitial definition.

Browser compatibility

BCD tables only load in the browser

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:126 次

字数:7845

最后编辑:8 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文