- DOM means Document Object Model.
- The DOM represents the elements on an HTML page as a tree.
- As an example (ref. Freeman and Robson, Headfirst JavaScript Programming, O'Reilley, 2014),
look at the body of this HTML page:
DOM Example:
<body>
<h1>Planetary Outpost Status Summaries</h1>
<ol>
<li>Green Planet<br>
All is well.</li>
<li class="redtext">Red Planet<br>
All systems A-OK.</p>
</ol>
<h2>Number of Planets</h2>
<p id="para">3</p>
</body>
- DOM for page representes as a traditional tree:
+--------- body ---------+
| / \ |
| / \ |
h1 ol h2 p
/ \
li li
- Traditionally trees are drawn upside down, with the root on top
and the leaves at the bottom.
- Here is an alternative representation with indentation with the child
relationship shown by indentation. In addition the inner HTML is also shown as a
child of its containing node.
body
h1
Planetary Outpost Status Summaries
ol
li
Green Planet<br>All is well.
li
Red Planet<br>All systems A-OK.
h2
Number of Planets
p
3
- Methods for finding HTML elements:
document.getElementById("123")
document.getElementsByTagName("input")
document.getElementsByClassName("redtext")
document.querySelector("li .redtext");
document.querySelectorAll("li .redtext");
- Properties of HTML elements:
innerHTML nodeName firstChild lastChild
childNodes previousSibling nextSibling
- Changing an attribute of an HTML element:
element.attributeName = "HTMLAttributeValue";
element.style.styleName = "cssStyleValue";
- Adding or deleting HTML elements:
document.createElement(element);
document.removeChild(element);
document.appendChild(element);
document.replaceChild(oldElement, newElement);
- Practice Problems:
For the Planetary Outpost Status Summaries page, show the output in this element
at the end of the document:
<p id="output" />
- Obtain the root node <html> and output its node name
(property nodeName). Remember to put your JavaScript
statements in an init method that is called after the
page is loaded. Answer:
var elements = document.getElementsByTagName("html");
var para = document.getElementById("output");
para.innerHTML = elements[0].nodeName;
- Print the number of elements with tagname li.
Answer:
var elements = document.getElementsByTagName("li");
var para = document.getElementById("output");
para.innerHTML = elements.length;
- Start with a body tag that looks like this:
<body />
- Add a paragraph to the body with the inner HTML
This is a test.
- Build this table entirely by using JavaScript:
| Name | Height | Country |
| Everest | 8849 | China/Nepal |
| Denali | 6190 | United States |
| Kilimanjaro | 5895 | Tanzania |