The Document Object Model (DOM) is an application programming interface (API) for HTML and XML documents.
The DOM represents a document as a hierarchical tree of nodes, allowing developers to add, remove, and modify individual parts of the page.
DOM is now a truly cross-platform, language-independent way of representing and manipulating pages for markup.
Any HTML document can be represented as a hierarchy of nodes using the DOM.
There are several node types, each representing different information and/or markup in the document.
For instance, consider the following HTML:
<html> <head> <title>Sample Page</title> </head> <body> <p>Hello World!</p> </body> </html>
The DOM tree for the code above.
Document | +--Element html | +--Element head | | | +--Element title | | | +--Text Sample Page +--Element body | +--Element p | +--Text Hello World!
A document node represents every document as the root. The document element is the outermost element in the document. There can be only one document element per document.
In HTML pages, the document element is always the html
element.
Every piece of markup can be represented by a node in the tree:
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 |
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 w ww . j ava 2 s . c o m-->
if (resultsElement.nodeType == 1){//works for all
document.writeln("Node is an element.");
}
</script>
</body>
</html>