Purpose of the DOM
The DOM organizes the content of a web page and provides a road map into it. The model is made up of nodes. Nodes are arranged into a hierarchy that’s best thought of as a tree structure. We should be able to take any HTML and represent it that way.
For example, the text of this paragraph is a node within the Document Object Model. The paragraph is another node and the parent to the text node. The document itself is ultimately a parent node to both of them.
Why is the source code for web pages managed this way? There are two main reasons:
The Nodes of the DOM
The nodes you create and control are limited to what the HTML specification and browsers support. That’s one reason that HTML5’s introduction of new top-level elements was important .
For our purposes, the most important types of nodes are:
Using a Script to Create Nodes in the DOM
Here we’ll show you how powerful JS is by using it to create one of the web’s most fundamental and common web page objects, the heading.
To follow along with this example, creating an entire virtual server is not worth the trouble , so use an online sandbox. You’ll want a light-weight playground to experiment with like JSBin. JSBin is great because it’s multi-paned, and includes a way to see and manipulate everything: HTML, JS, CSS, and the web page preview all at once.
(Codepen is similar, and for the sake of this example, will work just as well.)
JSBin can also dynamically create URLs for your JS scratchpad that can be shared later. Here’s the one I generated for this example.
I’ve reproduced and commented the following snippets to produce a new H1 heading in the body:
- HTML Snippet
//declare a new variable to hold a new h1 element var newHeading = document.createElement("h1"); //add the text node to the document var h1Text = document.createTextNode("Heading Level 1"); //make it a child node of the new heading newHeading.appendChild(h1Text); //append this as a child of element defined as "bt" document.getElementById("bt").appendChild(newHeading);
Which creates a new H1 element and its content directly subordinate to the <body> opening tag.
The above snippet bears a little explanation.
varcreates a variable, which stores an arbitrary value for your code to use.
=is an assignment operator. Here it operates with the
varterm and the new variable’s name (e.g., newHeading) to form a complete declaration.
object.methodis an invocation that uses “dot” syntax to separate objects, like the
document, from the methods being used in regard to them, as in
- The concept of “objects” in programming merits a lot of discussion and is outside the scope of this article. Suffice to say they are important components of your application.
- Methods are what you’d expect: a particular procedure or planned action that can be applied to the objects.
Image Credit: Imagentle via Shutterstock.com