JavaScript DOM Introduction

The Document Object Model (DOM) is a crucial concept that underpins the structure and interaction of web pages.

The DOM represents the hierarchical structure of HTML and XML documents, enabling JavaScript to access, manipulate, and update the content and style of web pages dynamically.

In this chapter, we'll explore the DOM in JavaScript, covering its fundamentals, traversal, manipulation, and event handling.

Understanding the DOM

The DOM is a programming interface provided by web browsers that represents the structure of web documents as a tree-like data structure.

Each node in the tree corresponds to an element, attribute, or text content of the document.

JavaScript interacts with the DOM to access and modify elements, allowing for dynamic updates to web pages based on user actions or application logic.

// Accessing the DOM
const heading = document.getElementById("heading");
console.log(heading.textContent); // Output: "Welcome to my website"         

Example

<!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Title of the Document</title>
      </head>
      <body>
        <h1 id="heading">Welcome to CodingKoleji</h1>
        <script>
          const heading = document.getElementById("heading");
          console.log(heading.textContent); // Output: "Welcome to my CodingKoleji"         
        </script>
      </body>
  </html>

DOM Traversal

Traversal refers to the process of navigating through the DOM tree to access specific elements or their relationships.

JavaScript provides various methods to traverse the DOM, such as getElementById(), getElementsByClassName(), getElementsByTagName(), querySelector() and querySelectorAll().

// Traversing the DOM
const listItems = document.querySelectorAll("li");

listItems.forEach(item => { 
  console.log(item.textContent);
})

In the above example we grab all the litags using the querySelectorAllmethod and then we display the content of them using listItems.textContent.

Example

<!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Title of the Document</title>
      </head>
      <body>
        <h1 id="heading">Welcome to CodingKoleji</h1>
        <ul>
          <li>Banana</li>
          <li>Orange</li>
          <li>Apple</li>
        </ul>
        <script>
          const listItems = document.querySelectorAll("li");

          listItems.forEach(item => { 
            console.log(item.textContent);
          })
        </script>
      </body>
  </html>

DOM Manipulation

Manipulating the DOM involves changing the structure, content, or style of elements dynamically.

JavaScript provides methods and properties to manipulate the DOM, including createElement(), appendChild(), removeChild(), setAttribute() and classListand more.

// Manipulating the DOM
const newListItem = document.createElement("li");

newListItem.textContent = "New Item";

document.querySelector("ul").appendChild(newListItem);

Example

<!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Title of the Document</title>
      </head>
      <body>
        <h1 id="heading">Welcome to CodingKoleji</h1>
        <ul>
          <li>Banana</li>
          <li>Orange</li>
          <li>Apple</li>
        </ul>
        <script>
          const newListItem = document.createElement("li");

          newListItem.textContent = "New Item";

          document.querySelector("ul").appendChild(newListItem);
          const listItems = document.querySelectorAll("li");

          listItems.forEach(item => { 
            console.log(item.textContent);
          })
        </script>
      </body>
  </html>

Event Handling

The event handling allows JavaScript to respond to user interactions such as clicks, keypresses, mouse movements, and form submissions.

Event listeners are used to register callback functions that execute in response to specific events.

// Event Handling
const button = document.getElementById("myButton");

button.addEventListener("click", () => {
  console.log("Button clicked!"); 
})

Example

<!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Title of the Document</title>
      </head>
      <body>
        <h1 id="heading">Welcome to CodingKoleji</h1>
        <button id="myButton">Click Me!</button>
        <script>
          const button = document.getElementById("myButton");

          button.addEventListener("click", () => {
            console.log("Button clicked!"); 
          })
        </script>
      </body>
  </html>

DOM Performance Considerations

Efficient DOM manipulation is crucial for optimizing web page performance.

Excessive DOM manipulation can lead to performance issues, especially on mobile devices or low-powered computers.

Techniques such as batch updates, using document fragments, and minimizing reflows and repaints can help improve DOM performance.

The DOM is a fundamental aspect of web development, enabling dynamic interaction and manipulation of web pages using JavaScript.

Let's learn about DOM methods in the next chapter.