DOM Node Type
Description
Every piece of markup can be represented by a node in the tree:
- HTML elements are represented by element nodes
- Attributes are represented by attribute nodes
- Document type is represented by a document type node
- Comments are represented by comment nodes
In total, there are 12 node types, all of which inherit from a base type.
DOM Level 1 has an interface called Node
implemented by all node types in the DOM.
The Node
interface is implemented in JavaScript as the Node type.
All node types inherit from Node
in JavaScript, so all node
types share the same basic properties and methods.
Every node has a nodeType property that indicates the type of node that it is. Node types are represented by one of the following 12 numeric constants on the Node type:
Type | Value |
---|---|
Node.ELEMENT_NODE | 1 |
Node.ATTRIBUTE_NODE | 2 |
Node.TEXT_NODE | 3 |
Node.CDATA_SECTION_NODE | 4 |
Node.ENTITY_REFERENCE_NODE | 5 |
Node.ENTITY_NODE | 6 |
Node.PROCESSING_INSTRUCTION_NODE | 7 |
Node.COMMENT_NODE | 8 |
Node.DOCUMENT_NODE | 9 |
Node.DOCUMENT_TYPE_NODE | 10 |
Node.DOCUMENT_FRAGMENT_NODE | 11 |
Node.NOTATION_NODE | 12 |
Node Type
A node's type is easy to determine by comparing against one of these constants:
<!DOCTYPE HTML>
<html>
<body>
<pre id="results"></pre>
<script>
var resultsElement = document.getElementById("results");
document.writeln(resultsElement.nodeType);
document.writeln(resultsElement.nodeName);
if (resultsElement.nodeType == Node.ELEMENT_NODE){
//won't work in IE < 9
document.writeln("Node is an element.");
} <!--from www .java2s. c o m-->
if (resultsElement.nodeType == 1){//works for all
document.writeln("Node is an element.");
}
</script>
</body>
</html>