DEV Community

Cover image for Everything You Need to Know About JavaScript DOM (Document Object Model)
Shefali
Shefali

Posted on • Edited on • Originally published at shefali.dev

Everything You Need to Know About JavaScript DOM (Document Object Model)

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)

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>
Enter fullscreen mode Exit fullscreen mode

Here's the javascript code:

 const paragraph = document.getElementById("paragraph");
  console.log(paragraph);
Enter fullscreen mode Exit fullscreen mode

Output will be as shown below:

JavaScript DOM (Document Object Model)

  • 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>
Enter fullscreen mode Exit fullscreen mode

Here's the javascript code:

const text = document.getElementsByClassName("text");
  console.log(text);
Enter fullscreen mode Exit fullscreen mode

Output will be as shown below:

JavaScript DOM (Document Object Model)

  • 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>
Enter fullscreen mode Exit fullscreen mode

Here's the javascript code:

const paragraph = document.getElementsByTagName("p");
  console.log(paragraph);
Enter fullscreen mode Exit fullscreen mode

Output will be as shown below:

JavaScript DOM (Document Object Model)

  • 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>
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Output will be as shown below:

JavaScript DOM (Document Object Model)

  • 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>
Enter fullscreen mode Exit fullscreen mode

Here's the javascript code:

  const text = document.querySelectorAll(".text");
  console.log(text);
Enter fullscreen mode Exit fullscreen mode

Output will be as shown below:

JavaScript DOM (Document Object Model)

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>
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Output:

JavaScript DOM (Document Object Model)

  • 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>
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Output:

JavaScript DOM (Document Object Model)

  • 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>
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Output:

JavaScript DOM (Document Object Model)

  • 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>
Enter fullscreen mode Exit fullscreen mode

JavaScript code:

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

console.log(altText);
Enter fullscreen mode Exit fullscreen mode

Output:

JavaScript DOM (Document Object Model)

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>
Enter fullscreen mode Exit fullscreen mode

JavaScript code:

const div = document.querySelector("div");
div.classList.add("active"); //Adds 'active' class
console.log(div);
Enter fullscreen mode Exit fullscreen mode

Output:

JavaScript DOM (Document Object Model)

  • 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>
Enter fullscreen mode Exit fullscreen mode

JavaScript code:

const div = document.querySelector("div");
console.log(div);
Enter fullscreen mode Exit fullscreen mode

Output:

JavaScript DOM (Document Object Model)

  • 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>
Enter fullscreen mode Exit fullscreen mode

JavaScript code:

const div = document.querySelector("div");
const containClass = div.classList.contains("active");
console.log(containClass);
Enter fullscreen mode Exit fullscreen mode

Output:

JavaScript DOM (Document Object Model)

  • 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>
Enter fullscreen mode Exit fullscreen mode

JavaScript code:

const div = document.querySelector("div");
const replaceClass = div.classList.replace("active","hidden");
console.log(div);
Enter fullscreen mode Exit fullscreen mode

Output:

JavaScript DOM (Document Object Model)

  • 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>
Enter fullscreen mode Exit fullscreen mode

JavaScript code:

const div = document.querySelector("div");
const removeClass = div.classList.remove("box"); //removes the 'box' class
console.log(div);
Enter fullscreen mode Exit fullscreen mode

Output:

JavaScript DOM (Document Object Model)

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>
Enter fullscreen mode Exit fullscreen mode

createElement()method creates a new element specified by the tag name.

const newElement = document.createElement('div');
Enter fullscreen mode Exit fullscreen mode

appendChild() method adds the newly created element to the document.

const newElement = document.createElement('div');
document.body.appendChild(newElement);
Enter fullscreen mode Exit fullscreen mode

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>';
Enter fullscreen mode Exit fullscreen mode

Let's create one more element into the document.

const newElement2 = document.createElement('p');
Enter fullscreen mode Exit fullscreen mode

Now append this element inside the div before created.

newElement.appendChild(newElement2);
Enter fullscreen mode Exit fullscreen mode

textContent property is used to add the text to the element.

newElement2.textContent = 'This is second created element.';
Enter fullscreen mode Exit fullscreen mode

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.';
Enter fullscreen mode Exit fullscreen mode

This will be the output:

JavaScript DOM (Document Object Model)

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>
Enter fullscreen mode Exit fullscreen mode

remove() method removes the element from the DOM completely.

const element = document.querySelector("h2");
element.remove();
Enter fullscreen mode Exit fullscreen mode

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

const parentElement = document.querySelector("div");
const childElement = document.querySelector("p");
parentElement.removeChild(childElement);
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

JavaScript code:

const heading = document.querySelector("h1");
heading.style.color = "red"; //This will change the color from black to red.
Enter fullscreen mode Exit fullscreen mode

Output:

JavaScript DOM (Document Object Model)

JavaScript code:

const button = document.querySelector("button");
button.style.backgroundColor = "green";
button.style.color = "white";
Enter fullscreen mode Exit fullscreen mode

Output:

JavaScript DOM (Document Object Model)

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>
Enter fullscreen mode Exit fullscreen mode

Get the button using querySelector() method (you can use any method of your choice).

const button = document.querySelector(".button");
Enter fullscreen mode Exit fullscreen mode

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!");
  });
Enter fullscreen mode Exit fullscreen mode

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
  });
Enter fullscreen mode Exit fullscreen mode

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.

Keep coding!!
Buy Me A Coffee

Top comments (0)