"Mastering the DOM: Elevate Your Web Development Game"

Anne MoigeAnne Moige
10 min read

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document's structure, style, and content. The DOM represents the document as nodes and objects, allowing programming languages to interact with the page. This representation enables a webpage to be manipulated. As an object-oriented representation, it can be modified with a scripting language like JavaScript.

Importance of Mastering DOM in Web Developmentevelopment

Mastering the DOM is crucial for web development because it allows developers to create dynamic and interactive web applications. By manipulating the DOM, developers can update content, structure, and styles, which enhances user experience and engagement. Understanding the DOM is also essential for working with JavaScript frameworks and libraries, which depend on it to work effectively.

The Role of the DOM in Web Development

The DOM serves as a bridge between the web page and the browser, enabling scripts to update the content, style, and structure of web documents. When a web page loads, the browser creates a DOM representation of the page. Each element (e.g., headers, paragraphs, links) is represented as an object that can be manipulated using scripting languages like JavaScript.

Structure of the DOM Tree

The DOM tree consists of nodes, where each node represents a part of the document, such as elements, attributes, text, and comments. This hierarchical structure allows developers to navigate and manipulate different parts of the document effectively.

Accessing and Manipulating DOM Elements Using JavaScript

You can access and manipulate DOM elements using several methods in JavaScript. Here are a few common ones:

  1. getElementById: This method references the first object with the specified ID. javascript let element = document.getElementById("myElementId");

  2. getElementsByClassName: This method returns a live HTMLCollection of all elements with the specified class name. javascript let elements = document.getElementsByClassName("myClassName");

  3. getElementsByTagName: This method returns a live HTMLCollection of all elements with the specified tag name. javascript let divs = document.getElementsByTagName("div");

  4. querySelector: This method returns the first element that matches a specified CSS selector. javascript let firstDiv = document.querySelector("div");

  5. createElement: This method creates an HTML element specified by the tag name. javascript let newElement = document.createElement("div");

Advanced Techniques: Manipulating DOM Attributes

You can also manipulate attributes of DOM elements, essential for creating interactive features. For example:

  • Setting an attribute: javascript newElement.setAttribute("class", "new class");

  • Getting an attribute: javascript let className = newElement.getAttribute("class");

  • Removing an attribute: javascript newElement.removeAttribute("class");

Using Libraries Like jQuery

Libraries like jQuery provide simplified methods to manipulate the DOM effectively. For example:

  • Selecting elements: javascript $("div.myClass").css("color", "blue");

  • Creating elements: javascript var newDiv = $("

    ").addClass("newClass");

  • Adding elements to the DOM: javascript $("body").append(new div);

DOM interfaces

This guide is about the objects and the actual things you can use to manipulate the DOM hierarchy. There are many points where understanding how these work can be confusing. For example, the object representing the HTML form element gets its namDOM interfaces This guide is about the objects and the actual things you can use to manipulate the DOM hierarchy. There are many points where understanding how these work can be confusing. For example, the object representing the HTML form element gets its name property from the HTMLFormElement interface but its className property from the HTMLElement interface. In both cases, the property you want is in that form object.

But the relationship between objects and the interfaces that they implement in the DOM can be confusing, and so this section attempts to say a little something about the actual interfaces in the DOM specification and how they are made available.

INTERFACES AND OBJECTS

Many objects implement several different interfaces. The table object, for example, implements a specialized HTMLTableElement interface, which includes such methods as createCaption and insertRow. But since it's also an HTML element, table implements the Element interface described in the DOM Element Reference chapter. And finally, since an HTML element is also, as far as the DOM is concerned, a node in the tree of nodes that make up the object model for an HTML or XML page, the table object also implements the more basic Node interface, from which Element derives.

When you get a reference to a table object, as in the following example, you routinely use all three of these interfaces interchangeably on the object, perhaps without knowing it.

JS Copy to Clipboard const table = document.getElementById("table"); const tableAttrs = table.attributes; // Node/Element interface for (let i = 0; i < tableAttrs.length; i++) { // HTMLTableElement interface: border attribute if (tableAttrs[i].nodeName.toLowerCase() === "border") { table.border = "1"; } } // HTMLTableElement interface: summary attribute table.summary = "note: increased border"; Core interfaces in the DOM This section lists some of the most commonly used interfaces in the DOM. The idea is not to describe what these APIs do here but to give you an idea of the sorts of methods and properties you will see very often as you use the DOM. These common APIs are used in the longer examples in the DOM Examples chapter at the end of this book.

The document and window objects are the objects whose interfaces you generally use most often in DOM programming. In simple terms, the window object represents something like the browser, and the document object is the root of the document itself. Element inherits from the generic Node interface, and together these two interfaces provide many of the methods and properties you use on individual elements. These elements may also have specific interfaces for dealing with the kind of data those elements hold, as in the table object example in the previous section.

The following is a brief list of common APIs in web and XML page scripting using the DOM.

document.querySelector() document.querySelectorAll() document.createElement() Element.innerHTML Element.setAttribute() Element.getAttribute() EventTarget.addEventListener() HTMLElement.style Node.appendChild() window.onload window.scrollTo() Examples Setting text content This example uses an element containing a and two <button> elements. When the user clicks the first button we set some text in the <textarea>. When the user clicks the second button we clear the text. We use:</p> <p>Document.querySelector() to access the <textarea> and the button EventTarget.addEventListener() to listen for button clicks Node.textContent to set and clear the text. HTML HTML Play Copy to Clipboard</p> <div class="container"> <textarea class="story"> Set text content Clear text content

CSS CSS Play Copy to Clipboard .container { display: flex; gap: 0.5rem; flex-direction: column; }

button { width: 200px; } JavaScript JS Play Copy to Clipboard const story = document.body.querySelector(".story");

const setText = document.body.querySelector("#set-text"); setText.addEventListener("click", () => { story.textContent = "It was a dark and stormy night..."; });

const clearText = document.body.querySelector("#clear-text"); clearText.addEventListener("click", () => { story.textContent = ""; });

Adding a child element. This example uses an element containing a and two elements. When the user clicks the first button we create a new element and add it as a child of the <div>. When the user clicks the second button we remove the child element. We use:Document.querySelector() to access the and the buttons EventTarget.addEventListener() to listen for button clicks Document.createElement to create the element Node.appendChild() to add the child Node.removeChild() to remove the child. HTML HTML Play Copy to Clipboard.p

Add a child Remove child CSS CSS Play Copy to Clipboard .container { display: flex; gap: 0.5rem; flex-direction: column; }

button { width: 100px; }

div.parent { border: 1px solid black; padding: 5px; width: 100px; height: 100px; }

div.child { border: 1px solid red; margin: 10px; padding: 5px; width: 80px; height: 60px; box-sizing: border-box; } JavaScript JS Play Copy to Clipboard const parent = document.body.querySelector(".parent");

const addChild = document.body.querySelector("#add-child"); addChild.addEventListener("click", () => { // Only add a child if we don't already have one // in addition to the text node "parent" if (parent.childNodes.length > 1) { return; } const child = document.createElement("div"); child.classList.add("child"); child.textContent = "child"; parent.appendChild(child); });

const removeChild = document.body.querySelector("#remove-child"); removeChild.addEventListener("click", () => { const child = document.body.querySelector(".child"); parent.removeChild(child); });e property from the HTMLFormElement interface but its className property from the HTMLElement interface. In both cases, the property you want is in that form object.

However the relationship between objects and the interfaces that they implement in the DOM can be confusing, and so this section attempts to say a little something about the actual interfaces in the DOM specification and how they are made available.

Interfaces and objects

Many objects implement several different interfaces. The table object, for example, implements a specialized HTMLTableElement interface, which includes such methods as createCaption and insertRow. But since it's also an HTML element, table implements the Element interface described in the DOM Element Reference chapter. And finally, since an HTML element is also, as far as the DOM is concerned, a node in the tree of nodes that make up the object model for an HTML or XML page, the table object also implements the more basic Node interface, from which Element derives.

When you get a reference to a table object, as in the following example, you routinely use all three of these interfaces interchangeably on the object, perhaps without knowing it.

JSCopy to Clipboard

const table = document.getElementById("table");
const tableAttrs = table.attributes; // Node/Element interface
for (let i = 0; i < tableAttrs.length; i++) {
  // HTMLTableElement interface: border attribute
  if (tableAttrs[i].nodeName.toLowerCase() === "border") {
    table.border = "1";
  }
}
// HTMLTableElement interface: summary attribute
table.summary = "note: increased border";

Core interfaces in the DOM

This section lists some of the most commonly-used interfaces in the DOM. The idea is not to describe what these APIs do here but to give you an idea of the sorts of methods and properties you will see very often as you use the DOM. These common APIs are used in the longer examples in the DOM Examples chapter at the end of this book.

The document and window objects are the objects whose interfaces you generally use most often in DOM programming. In simple terms, the window object represents something like the browser, and the document object is the root of the document itself. Element inherits from the generic Node interface, and together these two interfaces provide many of the methods and properties you use on individual elements. These elements may also have specific interfaces for dealing with the kind of data those elements hold, as in the table object example in the previous section.

The following is a brief list of common APIs in web and XML page scripting using the DOM.

Examples

Setting text content

This example uses a <div> element containing a <textarea> and two <button> elements. When the user clicks the first button we set some text in the <textarea>. When the user clicks the second button we clear the text. We use:

HTML

HTMLPlayCopy to Clipboard

<div class="container">
  <textarea class="story"></textarea>
  <button id="set-text" type="button">Set text content</button>
  <button id="clear-text" type="button">Clear text content</button>
</div>

CSS

CSSPlayCopy to Clipboard

.container {
  display: flex;
  gap: 0.5rem;
  flex-direction: column;
}

button {
  width: 200px;
}

JavaScript

JSPlayCopy to Clipboard

const story = document.body.querySelector(".story");

const setText = document.body.querySelector("#set-text");
setText.addEventListener("click", () => {
  story.textContent = "It was a dark and stormy night...";
});

const clearText = document.body.querySelector("#clear-text");
clearText.addEventListener("click", () => {
  story.textContent = "";
});

Adding a child element

This example uses a <div> element containing a <div> and two <button> elements. When the user clicks the first button we create a new element and add it as a child of the <div>. When the user clicks the second button we remove the child element. We use:

HTML

<div class="container">
  <div class="parent">parent</div>
  <button id="add-child" type="button">Add a child</button>
  <button id="remove-child" type="button">Remove child</button>
</div>

CSS

CSSPlayCopy to Clipboard

.container {
  display: flex;
  gap: 0.5rem;
  flex-direction: column;
}

button {
  width: 100px;
}

div.parent {
  border: 1px solid black;
  padding: 5px;
  width: 100px;
  height: 100px;
}

div.child {
  border: 1px solid red;
  margin: 10px;
  padding: 5px;
  width: 80px;
  height: 60px;
  box-sizing: border-box;
}

JavaScript

const parent = document.body.querySelector(".parent");

const addChild = document.body.querySelector("#add-child");
addChild.addEventListener("click", () => {
  // Only add a child if we don't already have one
  // in addition to the text node "parent"
  if (parent.childNodes.length > 1) {
    return;
  }
  const child = document.createElement("div");
  child.classList.add("child");
  child.textContent = "child";
  parent.appendChild(child);
});

const removeChild = document.body.querySelector("#remove-child");
removeChild.addEventListener("click", () => {
  const child = document.body.querySelector(".child");
  parent.removeChild(child);
});Conclusion

Understanding the DOM is a fundamental skill in web development. Mastering how to access and manipulate the document structure with JavaScript or libraries like jQuery allows developers to create rich, interactive user experiences on the web.

0
Subscribe to my newsletter

Read articles from Anne Moige directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anne Moige
Anne Moige

I am Anne Moige Musau, a passionate software engineering student at Moringa School. My journey in tech started with a strong interest in solving real-world problems through innovative solutions. I enjoy working on full-stack development, building projects that improve user experience, and continuously expanding my skill set.