Introduction

The DOM (Document Object Model) represents structure of HTML document in memory enabling manipulation of document using JavaScript. A document can be XML, HTML, SVG. The DOM is not part of the core JavaScript language.

Usually, the DOM is presented as a a logical tree, each tree has a node and each node has objects.

Nodes can have event handlers attatched to them and the handlers are fired once the event gets triggered.

A quick example

The DOM can be accessed by embedding script tag in a page, as:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <p id="alert"></p>
    <button id="btn">Click</button>
    <script>
      // some JavaScript to access the DOM here:
      window.onload = () => {
        const h1 = document.createElement("h1");
        const headingText = document.createTextNode("Hello World!");
        h1.appendChild(headingText);
        // append h1 tag to the body of the html
        document.body.appendChild(h1);

        // query an element by it's id
        const alertEl = document.getElementById("alert");
        // append some text
        alertEl.innerText = "Hello there, stranger!";
        const buttonEl = document.getElementById('btn')
        buttonEl.addEventListener("click", () => {
          // do something when the click event fires
          alert("hello!")
        })
      };
    </script>
  </body>
</html>

Try it out in the playground

With the advent to of modern JavaScript Frameworks direct DOM manipulation is unnecessary as libraries like Vue, Angular, Svelte and React provide an efficient way of handling DOM updates/manipulation when building Single Page Applications (SPAs)

That’s all. I’m working on the book titled: “A Modern JavaScript Primer”, please share your views here: 👉 What concepts do you find difficult to grasp in JavaScript?