Master the Art of DOM Manipulation - The Beginners Guide To Javascript(Part 7)
Tags: javascript, beginners, tutorial, programming
Published: 2023-04-26 16:25:25

## Introduction to the DOM: A Beginner's Guide

Welcome to the wonderful world of the Document Object Model, also known as the DOM! In this article, we'll take a look at what the DOM is and how to use it to manipulate web pages using JavaScript.

### What's the DOM?

The Document Object Model, or DOM for short, is a programming interface for web documents. When a web page is loaded, the browser creates a model of the page in memory. This model, or DOM tree, is a hierarchical representation of the HTML elements on the page, with each element represented by a node in the tree.

![HTML DOM](https://i.imgur.com/eYZbA6A.png)

Using JavaScript, we can interact with the DOM to manipulate the contents, attributes, and styles of the HTML elements on the page. This allows us to dynamically change the appearance and behavior of the page in response to user actions or other events.

### Using DevTools to Explore the DOM

Before we dive into manipulating the DOM with JavaScript, let's take a quick look at how to use the DevTools in your browser to explore the DOM.

To open DevTools, simply right-click anywhere on a web page and select "Inspect" from the context menu. This will open the DevTools panel, which includes a "Elements" tab that displays the DOM tree for the page.

![Chrome DevTools](https://i.imgur.com/nxadpzV.png)

From here, you can explore the structure of the DOM by expanding and collapsing nodes, and you can also edit the HTML and CSS of the page directly in the DevTools to see the effects in real-time.

### Selecting DOM Elements

To manipulate the DOM with JavaScript, we first need to be able to select the elements we want to target. There are several ways to select elements in the DOM using JavaScript, including selecting a single element by its id or by using a CSS selector, and selecting multiple elements using a variety of methods.

### Selecting a Single Element by its id

The most common way to select a single element in the DOM is by using its id attribute. To select an element by id, we use the document.getElementById() method, like so:

```javascript
const myElement = document.getElementById("my-id");
```

This will return a reference to the HTML element with the specified id, which we can then manipulate using JavaScript.

### Selecting a Single Element Using a CSS Selector

Another way to select a single element in the DOM is by using a CSS selector. To select an element using a CSS selector, we use the document.querySelector() method, like so:

```javascript
const myElement = document.querySelector(".my-class");
```

This will return a reference to the first HTML element on the page that matches the specified CSS selector. We can use any valid CSS selector with this method, allowing us to target elements based on their class, tag name, or any other CSS selector.

### Selecting Multiple Elements

To select multiple elements in the DOM, we can use a variety of methods, including `document.querySelectorAll()`, `document.getElementsByTagName()`, and `document.getElementsByClassName()`. These methods allow us to select multiple elements at once based on various criteria, such as their tag name, class name, or a combination of both.

For example, to select all the elements with a specific class name, we can use the `document.getElementsByClassName()` method, like so:

```javascript
const myElements = document.getElementsByClassName("my-class");
```

This will return a live HTMLCollection of all the elements on the page that have the specified class name, which we can then iterate over and manipulate using JavaScript.

### Changing the Content of an Element

Now that we know how to select elements in the DOM, let's look at how to change their content using JavaScript. There are several ways to change the content of an element, including setting its `innerHTML` property or its `textContent` property.

### Changing an Element's innerHTML Property

To change the content of an element using its `innerHTML` property, we simply assign a new value to the property, like so:

```javascript
const myElement = document.getElementById("my-id");
myElement.innerHTML = "<p>Hello, world!</p>";
```

This will replace the existing content of the element with the new HTML content specified.

### Changing an Element's textContent Property

To change the text content of an element, we use its `textContent` property, like so:

```javascript
const myElement = document.getElementById("my-id");
myElement.textContent = "Hello, world!";
```

This will replace the existing text content of the element with the new text specified.

### Changing the Style of an Element

In addition to changing the content of an element, we can also change its style using JavaScript. There are several ways to do this, including setting individual `style` properties using the style object, or adding or removing CSS classes using the `classList` property.

### Changing Individual Style Properties

To change individual style properties of an element, we use the style object, like so:

```javascript
const myElement = document.getElementById("my-id");
myElement.style.color = "red";
myElement.style.fontSize = "24px";
```

This will set the color and font size of the element to red and 24 pixels, respectively.

### Adding or Removing CSS Classes

To add or remove CSS classes from an element, we use the classList property, like so:

```javascript
const myElement = document.getElementById("my-id");
myElement.classList.add("my-class");
myElement.classList.remove("other-class");
```

This will add the "my-class" class to the element and remove the "other-class" class from it.

### Manipulating the Attributes of an Element

In addition to changing the content and style of an element, we can also manipulate its attributes using JavaScript. There are several ways to do this, including setting individual attribute values using the `setAttribute()` method, or getting or removing attribute values using the `getAttribute()` and `removeAttribute()` methods.

### Setting an Attribute Value

To set an attribute value of an element, we use the setAttribute() method, like so:

```javascript
const myElement = document.getElementById("my-id");
myElement.setAttribute("data-my-attribute", "my-value");
```

This will set the value of the `data-my-attribute` attribute of the element to "my-value".

### Getting an Attribute Value

To get the value of an attribute of an element, we use the `getAttribute()` method, like so:

```javascript
const myElement = document.getElementById("my-id");
const myAttributeValue = myElement.getAttribute("data-my-attribute");
console.log(myAttributeValue);
```

This will log the value of the `data-my-attribute` attribute of the element to the console.

### Removing an Attribute

To remove an attribute from an element, we use the `removeAttribute()` method, like so:

```javascript
const myElement = document.getElementById("my-id");
myElement.removeAttribute("data-my-attribute");
```

This will remove the `data-my-attribute` attribute from the element.

### Manipulating the Classes of an Element

As mentioned earlier, we can manipulate the classes of an element using the `classList` property. In addition to adding and removing classes, we can also toggle them using the `toggle()` method.

### Adding a Class

To add a class to an element, we use the add() method of the classList property, like so:

```javascript
const myElement = document.getElementById("my-id");
myElement.classList.add("my-class");
```

This will add the "my-class" class to the element.

### Removing a Class

To remove a class from an element, we use the remove() method of the classList property, like so:

```javascript
const myElement = document.getElementById("my-id");
myElement.classList.remove("my-class");
```

This will remove the "my-class" class from the element.

### Toggling a Class

To toggle a class on or off an element, we use the `toggle()` method of the `classList` property, like so:

```javascript
const myElement = document.getElementById("my-id");
myElement.classList.toggle("my-class");
```

This will toggle the "my-class" class on or off the element, depending on whether it is currently applied or not.

### Iterating Over a Collection of Elements

In addition to selecting individual elements, we can also select and manipulate collections of elements using JavaScript. There are several ways to do this, including using the `querySelectorAll()` method or accessing the `children` property of a parent element.

### Using `querySelectorAll()`

To select a collection of elements that match a specific CSS selector, we use the `querySelectorAll()` method, like so:

```javascript
const myElements = document.querySelectorAll(".my-class");
myElements.forEach((element) => {
  // Do something with each element
});
```

This will select all elements with the "my-class" class and execute the specified code for each element in the collection.

### Accessing the `children` Property

To select a collection of elements that are direct children of a parent element, we can access the `children` property of the parent element, like so:

```javascript
const myParentElement = document.getElementById("my-parent-id");
const myChildren = myParentElement.children;
for (let i = 0; i < myChildren.length; i++) {
  // Do something with each child element
}
```

This will select all direct children of the element with the "my-parent-id" and execute the specified code for each child element in the collection.

### Bonus Material

There is a lot more to learn about the DOM and how to manipulate it using JavaScript. Here are a few additional topics you might want to explore:

* Creating new elements and adding them to the DOM using the `createElement()` and `appendChild()` methods
* Using event listeners to respond to user interactions with the DOM
* Using animations and transitions to add polish to your web pages.

These topics barely scratch the surface of what you can do with the DOM and JavaScript. But by mastering the concepts we've covered here, you'll be well on your way to becoming a DOM manipulation expert!

### Conclusion

In this post, we covered the basics of DOM manipulation using JavaScript. We started by exploring what the DOM is and how it relates to HTML, then dove into the nitty-gritty details of selecting and manipulating DOM elements using JavaScript. Along the way, we covered a variety of important topics, including changing the content and style of elements, manipulating their attributes and classes, iterating over collections of elements, and more.

Hopefully, this post has helped demystify the DOM and given you a solid foundation to build upon as you continue to explore the exciting world of web development. So go forth and create amazing things with the power of the DOM at your fingertips!