JavaScript/Introduction to the Document Object Model (DOM)

HTML pages are internally implemented by a tree that contains the HTML elements (and CSS styles) as its nodes. This tree is called Document-Object Model, or DOM. JavaScript has full access to the DOM. It can navigate through the tree, modify the tree and nodes, ranging from simply adding new nodes to rearranging several areas on the page.

A hint about the terminology: Because of its closeness to XML, HTML uses the term element; and because of its structure as a tree, DOM uses the term node.

Nodes
When loading into the browser, the HTML document is broken down into a tree of nodes. For example, take a look at the following HTML snippet:

Through DOM, JavaScript sees this snippet as four nodes.
 * The, from its start tag through its end tag, is one node.  This   happens to have a property assigned inside its start tag.  This property is named "id" and has the value "exampleDiv".
 * The three other nodes in this example are inside the . They are called child nodes of the , because the   contains them.  Conversely, the   is their parent node.


 * The first child of the  is a text node, with the value "This is an". Text nodes contain only text; they never contain tags, which is why the tree stops here.
 * The  tag is another node.
 * The rest of the text is another text node.

Since the text nodes and the  tag all share the same parent, they are said to be sibling nodes.

Accessing nodes
You can access nodes of the DOM tree by various methods. One of them is.

When clicking on the button, the function  is called. It accesses the element with the id 'p2' and shows its content.

Accessing content
If you want to get access to the content of a node, you can use different properties of different classes:, , or. But they are not equal; please consider the differences. To keep our examples clear and easy, we use  whenever possible because it is very close to the HTML source code.

Changing content
After accessing a node, you can change its content by assigning a new value to its content.

When clicking on the button, the function  is called. Again, it accesses the element with the id 'p2' and changes its content.

Modifying the tree structure
JavaScript can manipulate the structure of the DOM tree.

When clicking on the button, the function  is called. It accesses the elements 'body' and 'p2', then, it moves the 'p' element to the end of the 'body'.