Day 66: Document Object Model
Tags: webdev, frontend, 100daysofcode, html
Published: 2023-10-11 15:49:48

### What is the DOM? 📜

The Document Object Model represents the structure of an HTML document in a tree-like form. In simpler terms, it's a programming interface for web documents, allowing programs (usually JavaScript) to interact with the web page's content. Each element in an HTML document, such as headings, paragraphs, images, forms, and more, becomes a part of this tree.

🌳 The DOM tree hierarchy often starts with the "document" object at the root, branching out into the HTML, head, and body elements, further subdividing into other elements. Consider the following example:

```html
<!DOCTYPE html>
<html>
  <head>
    <title>My Web Page</title>
  </head>
  <body>
    <h1>Hello, World!</h1>
    <p>Welcome to my website.</p>
  </body>
</html>
```

Here, the DOM tree would look like this:
```yaml
- Document
  - HTML
    - Head
      - Title
        - "My Web Page"
    - Body
      - H1 (Element)
        - "Hello, World!"
      - P (Element)
        - "Welcome to my website."
      - Text (Node)
      - Event Object
```

### DOM and JavaScript 🚀

JavaScript is the primary language used to interact with the DOM. It provides a way to access, manipulate, and modify the content and structure of a web page. To access the DOM from JavaScript, developers utilize a set of powerful APIs (Application Programming Interfaces). Let's explore some common tasks in the context of JavaScript.

### Fundamental Data Types and Their Usage 🧰

The DOM primarily deals with the following fundamental data types:

1. **Element**: Represents an HTML element, such as a `<div>` or an `<a>`.

2. **Node**: A generic term for any object in the DOM. Elements, attributes, text within elements, comments, and document itself are all types of nodes.

3. **Attribute**: Represents the properties of an element.

4. **Text**: Represents the textual content within an element.

5. **Document**: The top-level object representing the web page itself.

These data types allow you to interact with the web page's structure and content efficiently.


### DOM Interfaces 👥

The DOM provides various interfaces, each tailored for specific tasks. These interfaces expose methods and properties that enable you to interact with the DOM.

1. **Document Object**: Represents the web page itself and is often the entry point for DOM manipulation.

2. **Element Object**: Represents an HTML element and provides access to its attributes and methods.

3. **Node Object**: Represents a generic node in the DOM, allowing you to manipulate elements and their content.

4. **Event Object**: Provides information about events (e.g., mouse clicks, key presses) on the page and enables event handling.

| DOM Element      | Usage                                       | Properties/Methods                               |
|------------------|-----------------------------------------------------|---------------------------------------------------|
| **Element**      | `<div>`, `<p>`, `<a>`                               | `innerHTML`, `innerText`, `appendChild`          |
| **Node**         | Element, Attribute, Text, Comment, Document         | `parentNode`, `childNodes`, `nextSibling`        |
| **Attribute**    | `id`, `class`, `src`                                | `getAttribute()`, `setAttribute()`, `removeAttribute()`|
| **Text**         | Text within an HTML element                        | `nodeValue`, `textContent`                        |
| **Document**     | Represents the entire HTML document                 | `createElement()`, `getElementById()`, `querySelector()` |


### Accessing the DOM 🔍

To access a specific element in the DOM, you can use the `document` object along with various methods. Here's how you can select the `<h1>` element from our previous example:

```javascript
const heading = document.querySelector('h1');
```

You can also access elements by their `id` or `class` attributes:

```javascript
const elementById = document.getElementById('myElementId');
const elementsByClass = document.getElementsByClassName('myElementClass');
```

### Traversing the DOM 🚶‍♂️

Traversing the DOM means navigating from one element to another. JavaScript provides several methods to move around the DOM tree.

**Parent Node:**
```javascript
const paragraph = document.querySelector('p');
const parentElement = paragraph.parentNode;
```

**Child Node:**
```javascript
const body = document.body;
const children = body.children;
```

**Siblings:**
```javascript
const h1 = document.querySelector('h1');
const nextElement = h1.nextElementSibling;
const prevElement = h1.previousElementSibling;
```

**Finding Elements:**
```javascript
const container = document.querySelector('.container');
const listItem = container.querySelector('li');
```

### Examples 🌟

Let's put our knowledge to use with some examples:

#### **Changing Text Content**
```javascript
const paragraph = document.querySelector('p');
paragraph.textContent = 'Welcome to the new text!';
```

####  **Adding Elements**
```javascript
const newDiv = document.createElement('div');
newDiv.textContent = 'I am a new div!';
document.body.appendChild(newDiv);
```

#### **Handling Events**
```javascript
const button = document.querySelector('button');
button.addEventListener('click', () => {
  alert('Button clicked!');
});
```