“Brief” Guide to JavaScript – Part 5 | Blog of Jeff
“Brief” Guide to JavaScript – Part 5
July 6th, 2009DOM Tree
This part of the main reason of using JavaScript in the first place. Browsers give JavaScript access to its DOM, or Document Object Model, which is how the browser internalizes the HTML tree. This is an extremely large topic in its own right. A nice article in progress at Nettuts but otherwise you could probably find other resources on the internet besides this article. I wish I could go in-depth about DOM, but I would consume more than half this series (and JavaScript isn’t just about the DOM tree). Experimentation and online resources will help you plenty when wrangling with the DOM.
What is it?
The document object model is a tree-styled data structured which represents the html structure of a page. Browsers use DOM as a way to draw the page. Given this example HTML page:
<html> <head> <title>My title</title> </head> <body> <h1 id="header">My title</h1> <p>My paragraph text</p> <p id="secondpara">My second <strong>amazing</strong> paragraph.</p> </body> </html>.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }
When the browser loads this page, it generates a DOM tree close to the one shown below:
Before we start, we should quickly review some terminology of typical computer-science trees.
- Node: In the graph, a node is a box. They make up the tree itself.
- Leaf Node: Nodes that have no nodes underneath it.
- Internal Node: Nodes that contains more elements underneath it.
- Root: All nodes are “under” this node. For DOM trees, that’s the document node which is the root node for all html elements.
- Parent: A parent node is a node that is “above” the particular node we’re talking about. For example, the body node is the parent node to the h1 node.
- Child: A node that is directly underneath the node we’re talking about. The h1 node is a child node to the body node but the strong node would not be a child node to the body node.
- Sibling: Nodes that share the same parent node with the node we’re talking about. The h1 node has two sibling nodes, both of which are p nodes.
(As you can start to see, most of the naming schemes of trees are similar to family trees.)
Part 5 of my series (part 6 is later tonight)
Posted via web from Jeff Hui | Comment »