Nodes[edit | edit source]
DOM breaks up a document into a tree of nodes. For example, take a look at the following HTML snippet:
<div id="exampleDiv">This is an<br>example HTML snippet.</div>
- The div, from its start tag through its end tag, is one node. This div 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 div. They are called child nodes of the div, because the div contains them. Conversely, the div is their parent node.
- The first child of the div is a text node, with the value "This is an". Text nodes contain only text; they never contain tags, which is why the node stops here.
- The <br> tag is another node.
- The rest of the text is another text node.
Since the text nodes and the <br> tag all share the same parent, they are said to be sibling nodes.
Example[edit | edit source]
What the above example would do would be similar to the following:
<html> <head> </head> <body> <p id="DOMEx"><div id="DOMExample"></div></p> </body> </html>
Explanation[edit | edit source]
This code rearranges the HTML, moving the
<div> tag from a sibling of the
<p> tag to its child. Here's how that works:
First, the two nodes are found by the use of the DOM function
document.getElementById(). The nodes are assigned to two variables. Variable
div finds the first tag with the ID property
p finds the first tag with the ID
DOMEx, which, in this example, is the
p.appendChild() uses the
appendChild function to place the value of
div under the node associated with p, as its last child. In other words, it puts the
div tag inside the