DEV Community

shunku
shunku

Posted on

Chapter 6: JavaScript and the Document Object Model (DOM)

What is the DOM?

The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document (such as a webpage) and allows programs to manipulate the document's structure, style, and content. In essence, the DOM represents a document as a tree-like structure made up of nodes. Each node represents part of the document (e.g., an element, an attribute, the text within an element, etc.).

Here's a simple HTML document and its DOM representation:

<!DOCTYPE html>
<html>
<head>
  <title>My Title</title>
</head>
<body>
  <h1>My Heading</h1>
  <p>My paragraph.</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

This can be visualized as a tree:

Document
├── DOCTYPE: html
├── html
│   ├── head
│   │   └── title
│   │       └── "My Title"
│   └── body
│       ├── h1
│       │   └── "My Heading"
│       └── p
│           └── "My paragraph."
Enter fullscreen mode Exit fullscreen mode

Traversing and Manipulating the DOM

JavaScript can be used to traverse (navigate through) and manipulate (change) the DOM.

For example, you can select an element in the DOM using JavaScript:

let heading = document.querySelector('h1'); // Selects the first h1 element
Enter fullscreen mode Exit fullscreen mode

And you can change the content of an element:

heading.textContent = 'New Heading'; // Changes the text of the h1 element
Enter fullscreen mode Exit fullscreen mode

You can also create new nodes and add them to the DOM:

let newParagraph = document.createElement('p'); // Creates a new p element
newParagraph.textContent = 'New paragraph.'; // Adds text to the new p element
document.body.appendChild(newParagraph); // Adds the new p element to the body
Enter fullscreen mode Exit fullscreen mode

Event Handling

Events are actions or occurrences that happen in the browser, often as a result of user interaction. JavaScript can listen for these events and execute code in response.

To listen for an event, you use the addEventListener method, specifying the type of event and a function that should be run when the event occurs. This function is often called an event handler or event listener.

let button = document.querySelector('button'); // Selects the button element

button.addEventListener('click', function() {
  alert('Button was clicked!');
});
Enter fullscreen mode Exit fullscreen mode

In this example, when the button is clicked, the browser will alert the user with a message saying "Button was clicked!".

The combination of JavaScript and the DOM is incredibly powerful. It's the foundation of how all modern websites and web applications create interactive experiences for users.

Top comments (0)