To change a page, JavaScript needs a way to reach its elements. The Document Object Model provides it.
The DOM
The Document Object Model (DOM) is a tree-shaped representation of an HTML page that the browser builds when it loads the page. Each element, attribute and piece of text is a node in the tree. The document object is the root. JavaScript can read and change any node, so changes to the DOM appear at once on the page. The DOM is a standard of the W3C and WHATWG, and works the same in all browsers.
Definition: Document Object Model. A tree-structured, programmable representation of an HTML document in which every element and piece of text is a node that JavaScript can read and change.
Selecting Elements
document.getElementById("id") returns the element with that id. document.getElementsByClassName("c") and getElementsByTagName("p") return live collections. document.querySelector("css selector") returns the first element matching any CSS selector, and querySelectorAll() returns all of them as a NodeList, which can be looped with forEach.
Traversing the DOM
From any element, JavaScript can move around the tree. parentElement (or parentNode) gives the parent. children gives the child elements, with firstElementChild and lastElementChild. nextElementSibling and previousElementSibling give the neighbours. (The properties childNodes, firstChild and nextSibling also include text nodes, such as spaces.) Traversal is used, for example, to find the row that contains a clicked button, or to step through all items of a list.
Changing the DOM
textContent sets plain text, and innerHTML sets HTML. setAttribute() and getAttribute() change attributes, and properties such as src, href and value can be set directly. element.style.property changes inline styles, and classList.add(), remove() and toggle() change classes. document.createElement() creates a new element, appendChild() or append() adds it to the tree, and remove() deletes an element.
Table 3.5: DOM selection and traversal
| Task | Method or property | Returns |
|---|---|---|
| By id | getElementById("x") | One element |
| By CSS selector | querySelector(".c li") | First match |
| All matches | querySelectorAll("li") | NodeList |
| Parent / children | parentElement, children | Element, collection |
| Siblings | nextElementSibling | Element or null |
Example 3.5: Building and traversing a list
Problem: Add three subjects to a list using the DOM, then traverse the list to number its items and highlight the last one.
Solution:
- Create each <li> with createElement, set textContent and append it to the <ul>.
- Loop through ul.children, prefixing each with its number.
- Use lastElementChild to highlight the last item.
Result: The list shows "1. HTML", "2. CSS", "3. JavaScript", with the last highlighted.
<ul id="subjects"></ul>
<script>
const ul = document.getElementById("subjects");
for (const s of ["HTML", "CSS", "JavaScript"]) {
const li = document.createElement("li");
li.textContent = s;
ul.appendChild(li);
}
[...ul.children].forEach((li, i) =>
li.textContent = (i + 1) + ". " + li.textContent);
ul.lastElementChild.style.background = "yellow";
const second = ul.firstElementChild.nextElementSibling;
console.log(second.textContent); // 2. CSS
</script>
Common mistakes
- Running a script that selects elements before they have loaded.
- Using innerHTML with text typed by users, which can allow script injection; use textContent.
- Expecting getElementById to need a # sign. It takes the bare id.
Key takeaways
- The DOM is a tree of nodes built from the page.
- Select with getElementById, querySelector and querySelectorAll.
- Traverse with parentElement, children and sibling properties.
- Change with textContent, innerHTML, style, classList, createElement and appendChild.
Practice questions
- What is the DOM?
- What does querySelector return?
- How do you move to the parent of an element?
Answers to the practice questions
- A tree representation of the HTML page in which every element is a node that scripts can read and change.
- The first element that matches the given CSS selector.
- With the parentElement property.
Sources
- Official BCA syllabus Web Technologies, course code 25BCA402SEC02, Unit III
