What is the JavaScript HTML DOM?

Key takeaways:

  • The Document Object Model (DOM) is a virtual layout that displays the structure and content of a file, shows the elements in it, and allows alterations to them.

  • The HTML DOM is a DOM applied to an HTML file, also known as a web page.

  • HTML elements are objects that are part of a collection of nodes. They act as points within an interconnected network. The easiest way to locate an HTML element is with its ID, which is unique and cannot be replicated.

  • The JavaScript HTML DOM is an HTML DOM that is accessed using the programming language JavaScript. Alterations to the DOM include creating, deleting, and changing the elements.

Imagine a webpage as a tree, where each element like headers, paragraphs, links, and images are branches. With JavaScript, we can “climb” this tree to access and modify any element or structure on the page. The DOM allows JavaScript to interact dynamically with the content, structure, and style of a webpage, creating a seamless experience for users by allowing real-time updates and changes to the webpage without reloading it.

Introduction to the HTML DOM

The HTML DOM (Document Object Model) is a programming interface provided by browsers that allows JavaScript to interact with HTML documents. It acts as a map for the webpage, where each HTML element becomes an object, creating a tree-like structure. This structure lets JavaScript add, delete, modify, or respond to user interactions in real time, making the web experience dynamic.

The DOM isn’t limited to JavaScript; other languages, like Python or Java, can also manipulate the DOM. However, JavaScript is the most commonly used for client-side web interactions.

DOM structure and terminology

The HTML document is structured as a tree, where each HTML element (tag) represents a node. These nodes form relationships:

  • Document node: The root node representing the entire HTML document.

  • Element nodes: HTML tags like <html>, <body>, <div>, etc., each becoming an individual node.

  • Text nodes: The text inside HTML tags becomes a text node, holding actual content.

  • Attributes: Elements can have attributes (like class or id) that provide additional properties.

Example

Let’s have an example of a simple HTML structure and its corresponding DOM tree:

  • HTML
Using HTML IDs

In the above HTML code:

  • <!DOCTYPE html>: This declaration specifies the HTML version and ensures the browser renders the page in standards mode.

  • <html>: The root element of the document, which houses all content and metadata.

  • <head>: Contains metadata about the document, including title, styles, and other head elements. This data is essential for SEO and site functionality but isn’t displayed on the page itself.

    • <meta name="description" content="...">: Provides a brief description of the page’s content, which can improve SEO by helping search engines understand the topic.

    • <title>: Specifies the title of the page, displayed in the browser’s title bar or tab.

  • <body>: This element holds the visible content of the webpage.

    • <div id="header">: A container (div) with an id attribute. IDs uniquely identify elements in the DOM, useful for accessing them through JavaScript.

      • <h1>: The first-level heading displays the text “The JavaScript HTML DOM.”

      • <p>: The paragraph displays the text “This is a sample paragraph”

    • <button id="onBtn">: A button element with the label “ON” and an id attribute for easy access.

    • <button id="offBtn">: Another button element with a different label (“OFF”) and a unique id.

DOM tree

Here is a diagram of the HTML DOM element layout:

HTML DOM element layout
HTML DOM element layout

The DOM is language-neutral. Therefore, instead of just using Javascript, we can also use a different language to access the DOM. For example, we can use Python.

Accessing elements in the DOM

This HTML structure becomes a DOM tree where JavaScript can access each element. JavaScript provides several methods to access elements in the DOM, allowing us to select elements by their tag name, class name, ID, or CSS selectors.

Using the getElementById() method

The getElementById() method accesses a single element by its unique id.

const button = document.getElementById("onBtn");

Using this method, we can interact with elements using their IDs and modify them according to the requirements.

Using the getElementByClassName() method

The getElementsByClassName() method returns all elements with a specified class name in a collection.

const items = document.getElementsByClassName("item");

We can use the above method to access elements with a specific class.

Using the getElementByTagName() method

The getElementsByTagName() method selects all elements with a specific tag name.

const paragraphs = document.getElementsByTagName("p");

To access all paragraph elements, we can use the getElementsByTagName() method as above.

Using the querySelector() method

The querySelector() method selects the first element that matches a specified CSS selector.

const firstHeading = document.querySelector(".h1");

To access the first heading (<h1>), we can use the querySelector() method as above.

Using the querySelectorAll() method

The document.querySelectorAll() method returns a collection of all elements matching a specified CSS selector.

const allHeadings = document.querySelectorAll(".h1");

We use the above method to access all heading elements.

Manipulating elements in the DOM

Once we have access to an element, we can manipulate it—change its content, style, or even add/remove elements.

Changing context and attributes

Let’s have an example of changing the context and attributes of different elements.

  • HTML
  • JavaScript
Changing context and attributes in the DOM

In the above JavaScript code:

  • Lines 2–3: We access the <h1> elements within the element that has the ID header and update the text of the first <h1> element by setting its innerText property to “Updated Heading Text”. This changes the visible text displayed on the web page.

  • Lines 4–5: We similarly access the first <p> element within the header and update the text of this paragraph by setting its textContent property to “This is the updated paragraph.”. This changes the content displayed in the paragraph.

  • Lines 8–9: We access the button with the ID onBtn and change the background color of the “ON” button by setting its style.backgroundColor property to green. This visually indicates an active state for this button.

  • Lines 10–11: Similarly, we access the button with the ID offBtn in the same way and set its background color to red.

Adding and removing elements

Let’s have another example of adding and removing elements in DOM.

  • HTML
  • JavaScript
Adding and removing in the DOM

In the above code:

  • Line 2: We create a new <div> element using the document.createElement("div") method. This method generates a new HTML element that we can manipulate before adding it to the DOM.

  • Line 3: We use the innerText property to set the text content of the newly created <div> to “This is a new div.”.

  • Line 4: We call the appendChild() method on document.body, which appends the new <div> as the last child of the body. This effectively adds a new element to the visible webpage.

  • Lines 7–8: We select the button with the ID onBtn and call the remove() method to remove it from the DOM, effectively deleting it from the webpage.

  • Lines 9–10: Similarly, we select the button with the ID offBtn and remove it.

Event handling in the DOM

Events in the DOM are actions that can trigger JavaScript functions, such as clicks, key presses, or form submissions. Handling events allows us to create interactive web experiences.

  • HTML
  • JavaScript
Adding a click event listener

In the above code:

  • Line 1: We select the button with the ID myButton and store it in the button.

  • Lines 2–4: We add a click event listener that triggers an alert when the button is clicked.

Common event types

  • click: Fired when an element is clicked.

  • mouseover: Fired when the mouse is over an element.

  • keydown: Fired when a key is pressed.

  • submit: Fired when a form is submitted.

Knowledge test

Let’s attempt a short quiz to assess your understanding.

Q

How can you remove an element in the DOM?

A)

removeChild()

B)

removeElement()

C)

remove()

D)

removeElementById()

Conclusion

The JavaScript HTML DOM is essential for building interactive, user-friendly web pages. By allowing JavaScript to access and modify HTML documents in real time, the DOM empowers developers to create responsive, engaging user experiences.


Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is innerHTML in JavaScript?

The innerHTML is a property of DOM elements that allows you to get or set the HTML content within an element. When you use element.innerHTML, it returns the HTML markup contained within the element as a string. Conversely, you can assign a string of HTML to innerHTML to update the element’s content dynamically. For example:

const element = document.getElementById("example");
element.innerHTML = "<p>This is a new paragraph.</p>"; // Updates the inner HTML of the element

Caution: While using innerHTML is convenient for inserting HTML, it can expose your site to Cross-Site Scripting (XSS) attacks if you’re inserting untrusted content. Always sanitize any user input that will be inserted into the DOM.


What is DOM vs. HTML?

  • HTML (HyperText Markup Language) is the standard markup language used to create the structure and content of web pages. It defines the elements (like headings, paragraphs, links, etc.) that appear on a page, but it is static and does not provide interactivity.
  • DOM (Document Object Model) is a programming interface for web documents. It represents the structure of a document as a tree of objects, where each object corresponds to an HTML element. The DOM allows programming languages (like JavaScript) to interact with the document, enabling dynamic content updates, event handling, and more. In other words, while HTML is the content of a webpage, the DOM is the structure that allows you to manipulate that content programmatically.

How to create a DOM in HTML?

The DOM is automatically created by the browser when an HTML document is loaded. Every time you load an HTML page, the browser parses the HTML and generates a corresponding DOM structure. However, you can manipulate this DOM using JavaScript. For example, to create and add new elements to the DOM dynamically, you can use methods like document.createElement() and appendChild(). Here’s a simple example:

<!DOCTYPE html>
<html>
  <head>
    <title>Creating DOM Example</title>
  </head>
  <body>
    <button onclick="addNewElement()">Add Element</button>
    <script>
      function addNewElement() {
        const newDiv = document.createElement("div"); // Create a new div
        newDiv.innerText = "This is a new div."; // Set its content
        document.body.appendChild(newDiv); // Append it to the body
      }
    </script>
  </body>
</html>

In this example, clicking the button will trigger the addNewElement() function, which creates a new <div> and appends it to the body of the document, thus modifying the DOM dynamically.


Free Resources