Everything You Need to Know About JavaScript DOM (Document Object Model)
Tags: webdev, javascript, beginners, programming
Published: 2023-07-17 12:49:44

## Introduction
JavaScript is an essential programming language that allows developers to create dynamic and interactive web pages. The Document Object Model (DOM) is a key feature of JavaScript, allowing developers to effectively manipulate and interact with web pages.

In this blog post, we will explore various aspects of DOM manipulation such as selecting and modifying elements in the document, creating and removing elements, manipulating element styles and handling events.

## What is the DOM?
The Document Object Model (DOM) is a programming interface that allows us to select and modify elements, create and remove elements and manipulate element styles in the document.

DOM represents the structure of an HTML document as a tree-like structure. The document is the root of the tree and contains one child node that is `<html>` element. Within the `<html>` element, there are two children: the `<head>` and `<body>` elements. The `<head>` and `<body>` elements contain their respective children.


![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0furoiapev34oyj7kjqs.png)

## Selecting Elements in the Document
The DOM provides the following methods to select elements.

- `getElementById()` selects the element by its unique id.

```
<!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="paragraph">This is paragraph.</p>
    </body>
  </html>
```
Here's the javascript code:

```
 const paragraph = document.getElementById("paragraph");
  console.log(paragraph);
```
Output will be as shown below:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ozvgg61wtrksgs7lnu0d.png)

- `getElementsByClassName()` selects elements by their class name.

```
  <!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>
      <h1 class="text">This is heading.</h1>
      <p class="text">This is paragraph.</p>
    </body>
  </html>
```
Here's the javascript code:

```
const text = document.getElementsByClassName("text");
  console.log(text);
```
Output will be as shown below:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tdzts2uho6ugtkgarf4q.png)

- `getElementsByTagName() `selects elements by their tag name.

```
  <!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>This is paragraph.</p>
    </body>
  </html>
```
Here's the javascript code:

```
const paragraph = document.getElementsByTagName("p");
  console.log(paragraph);
```
Output will be as shown below:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ki8fm9e86aixgze9ut1q.png)

- `querySelector()` selects the first element that matches the specified CSS selector.


```
 <!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>
      <header>
        <h1 class="heading1">This is first heading.</h1>
        <h2 id="heading2">This is second heading.</h2>
      </header>
    </body>
  </html>
```
Here's the javascript code:

```
 const header = document.querySelector("header");
  const heading1 = document.querySelector(".heading1");
  const heading2 = document.querySelector("#heading2");
  console.log(header);
  console.log(heading1);
  console.log(heading2);
```
Output will be as shown below:


![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8noplc2sxfdkdtf8c2ug.png)

- `querySelectorAll()` selects all elements that matches the specified CSS selector.
```
  <!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>
      <h1 class="text">This is first heading.</h1>
      <h2 class="text">This is second heading.</h2>
    </body>
  </html>
```
Here's the javascript code:

```
  const text = document.querySelectorAll(".text");
  console.log(text);
```

Output will be as shown below:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uvt5jdvqcgk14hrb89pe.png)

## Modifying Attributes of Selected Elements
The DOM provides the following methods to modify attributes of selected elements.

- `getAttribute()` returns the value of the specified attribute.

```
 <!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>
      <h1 class="heading">This is heading.</h1>
      <img src="image.jpg" >
    </body>
  </html>
```
JavaScript code:

```
  const heading = document.querySelector(".heading")
  const img = document.querySelector("img");

  const className = heading.getAttribute("class");
  const imgSrc = img.getAttribute("src");

  console.log(className);
  console.log(imgSrc);
```
Output:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oow72lsjy82b0wwc4ga2.png)

- `hasAttribute() `returns true or false.

```
<!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>
      <h1>This is heading.</h1>
      <img src="image.jpg" >
    </body>
  </html>
```

JavaScript code:


```
const heading = document.querySelector("h1")
  const img = document.querySelector("img");

  const className = heading.hasAttribute("class");
  const imgSrc = img.hasAttribute("src");

  console.log(className);
  console.log(imgSrc);
```
Output:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6fz8gggd93lvauiyfxvc.png)

- `setAttribute()` sets the value of the specified attribute.

```
<!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>
      <img src="image.jpg" >
    </body>
  </html>
```
JavaScript code:

```
  const img = document.querySelector("img");
  //syntax for setAttribute:
  //setAttribute(name,value);
  const imgAlt = img.setAttribute("alt","picture");

  const altText = img.getAttribute("alt");

  console.log(altText);
```
Output:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wo2loziv1srprd66dwl5.png)

- `removeAttribute()` removes the specified attribute.

```
<!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>
    <img src="image.jpg" alt="picture">
  </body>
</html>
```
JavaScript code:

```
const img = document.querySelector("img");
const removeAlt = img.removeAttribute("alt");
const altText = img.getAttribute("alt");

console.log(altText);
```
Output:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h0rgrehizcojgk1qevm0.png)

## Modifying Classes of Selected Elements
The DOM provides the following methods to modify classes of selected elements.

- `classList.add()`adds a class.

```
<!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>
    <div>Div</div> <!-- No class present here -->
  </body>
</html>
```
JavaScript code:

```
const div = document.querySelector("div");
div.classList.add("active"); //Adds 'active' class
console.log(div);
```
Output:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/osbxlmy1bnfxudi166hd.png)

- `classList.toggle()` toggles a class on or off.

```
<!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>
    <div>Div</div>
  </body>
</html>
```
JavaScript code:

```
const div = document.querySelector("div");
console.log(div);
```
Output:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/frtd1epn8qbv17i3q9pt.png)

- `classList.contains()` checks if class value exists.

```
<!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>
    <div>Div</div>
  </body>
</html>
```
JavaScript code:

```
const div = document.querySelector("div");
const containClass = div.classList.contains("active");
console.log(containClass);
```
Output:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pd4htajlgtw7sk5igko3.png)

- `classList.replace()` replace existing class value with new class value.

```
<!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>
    <div class="active">Div</div>
  </body>
</html>
```
JavaScript code:

```
const div = document.querySelector("div");
const replaceClass = div.classList.replace("active","hidden");
console.log(div);
```
Output:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wz11ow918roe1k6ohz3k.png)

- `classList.remove()` remove a class value.

```
<!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>
    <div class="active box">Div</div> <!-- two classes present here -->
  </body>
</html>
```
JavaScript code:

```
const div = document.querySelector("div");
const removeClass = div.classList.remove("box"); //removes the 'box' class
console.log(div);
```
Output:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5m2ejl2nt2hrr7lttrlo.png)

## Adding New Elements
Here's the basic structure of the HTML document.

```
<!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>
    <h1>Hello World!</h1>
  </body>
</html>
```
`createElement()`method creates a new element specified by the tag name.

```
const newElement = document.createElement('div');
```
`appendChild()` method adds the newly created element to the document.

```
const newElement = document.createElement('div');
document.body.appendChild(newElement);
```
`innerHTML` property sets the HTML content of the element.

```
const newElement = document.createElement('div');
document.body.appendChild(newElement);
newElement.innerHTML = '<h1>This is newly created div heading.</h1>';
```
Let's create one more element into the document.

```
const newElement2 = document.createElement('p');
```
Now append this element inside the div before created.

```
newElement.appendChild(newElement2);
```
`textContent` property is used to add the text to the element.

```
newElement2.textContent = 'This is second created element.';
```

Putting it all together:

```
const newElement = document.createElement('div');
document.body.appendChild(newElement);
newElement.innerHTML = '<h1>This is newly created div heading.</h1>';
const newElement2 = document.createElement('p');
newElement.appendChild(newElement2);
newElement2.textContent = 'This is second created element.';
```
This will be the output:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y6lm8gwc46eeqztc8ubh.png)

## Removing Elements
Here's the basic structure of the HTML document.

```
<!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>
      <h1>Hello World!</h1>
    <div>
      <h2>This is heading inside div.</h2>
      <p>This is paragraph inside div.</p>
    </div>
  </body>
</html>
```
`remove()` method removes the element from the DOM completely.

```
const element = document.querySelector("h2");
element.remove();
```

`removeChild()` method removes a child element from its parent element.

```
const parentElement = document.querySelector("div");
const childElement = document.querySelector("p");
parentElement.removeChild(childElement);
```

## Manipulating Element Styles
You can change the style of any element using `style` property.

Here's the basic structure of the HTML document.

```
<!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>
      <h1>Hello World!</h1>
      <button>Click me!</button>
  </body>
</html>
```
JavaScript code:

```
const heading = document.querySelector("h1");
heading.style.color = "red"; //This will change the color from black to red.
```
Output:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qc1z864adav8pnbuaecf.png)

JavaScript code:

```
const button = document.querySelector("button");
button.style.backgroundColor = "green";
button.style.color = "white";
```
Output:

![JavaScript DOM (Document Object Model)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ikyvtsneg8pibteip35o.png)

Similarly, you can change the other styles of the elements using the style property.

When modifying the style of elements using the DOM, always keep in mind to use the property names with camel case. For example, instead of using "font-size," use "fontSize," and instead of "background-color," use "backgroundColor."

## Handling Events
Here's the basic structure of the HTML document.

```
<!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>
      <button class="button">Click me!</button>
  </body>
</html>
```
Get the button using `querySelector()` method (you can use any method of your choice).

```
const button = document.querySelector(".button");
```
The `addEventListener()` method is used to attach an event handler function to an HTML element.

The `addEventListener()` method takes in an event type and a function.

```
const button = document.querySelector(".button");
button.addEventListener("click", () => {
    alert("I'm clicked!");
  });
```

Here's another example:

```
const button = document.querySelector(".button");
button.addEventListener("mouseover", () => {
    button.style.color = "red"; //This will change the color of the text on mouse over
  });
```

## Conclusion
The Document Object Model (DOM) is a key feature of JavaScript, allowing developers to effectively manipulate and interact with web pages. DOM manipulation has various aspects such as selecting and modifying elements in the document, creating and removing elements, manipulating element styles and handling events.

You can select the elements using `getElementById()` , `getElementsByClassName()` , `getElementsByTagName()` , `querySelector()` and `querySelectorAll()` methods.

For modifying the attributes of selected elements, you can use `getAttribute()` , `hasAttribute()` , `setAttribute()` and `removeAttribute()` methods.

To modify the classes of selected elements, you can use `classList.add()` ,`classList.toggle()` , `classList.contains()` , `classList.replace()` and `classList.remove()` methods.

You can create new element using `createElement()` method and append it to the document using `appendChild()` method.

To remove elements, you can use `remove()` method and `removeChild()` method.

To change the style of any element use style property.

You can handle events using `addEventListener()` method.

Thanks for reading.

For more content like this [click here](https://shefali.dev/blog).

Keep coding!!
<a href="https://www.buymeacoffee.com/devshefali" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>