In JavaScript, the Document Object Model (DOM) allows you to create dynamic and interactive web pages by manipulating elements.
What is the Document Object Model (DOM)?
The Document Object Model (DOM) allows you 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.
Selecting Elements in the Document
The DOM provides the following methods to select elements.
getElementById(): selects the element by its unique id
HTML Structure:
<!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>
Select the element by its id
:
const paragraph = document.getElementById("paragraph");
console.log(paragraph);
Output:
Here, document.getElementById("paragraph")
method searches the entire HTML document for an element with the id
of paragraph
. It returns a reference to that element (if found), or null
if no such element exists.
getElementsByClassName(): selects elements by their class name
HTML Structure:
<!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>
Select the element by its class
:
const text = document.getElementsByClassName("text");
console.log(text);
Output:
Here, document.getElementsByClassName("text")
method searches the entire HTML document for all elements that have the class name text
. It returns an HTMLCollection (not a single element and not null). If none are found, it logs an empty collection ([]
).
getElementsByTagName(): selects elements by their tag name
HTML Structure:
<!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>
Select the element by its tag name:
const paragraph = document.getElementsByTagName("p");
console.log(paragraph);
Output:
Here, document.getElementsByTagName("p")
method searches the entire HTML document for all elements that have the tag name p
. It returns an HTMLCollection (even if there's only one). If no <p>
tags exist, it logs an empty collection ([]
).
querySelector(): selects the first element that matches the specified CSS selector
HTML Structure:
<!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>
Select the first element that matches the specified CSS selector:
To select:
- Tag name: write as is (e.g. "header")
- Class: use a dot
.
before the name (e.g. ".heading1") - id: use a hash
#
before the name (e.g. "#heading2")
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:
Here,
-
document.querySelector()
selects the first matching element for the given CSS selector.- "header": first
<header>
tag - ".heading1": first element with class
heading1
- "#heading2": element with id
heading2
- "header": first
-
If a match is found, the element is returned, otherwise,
null
. -
Each
console.log(...)
prints the selected element ornull
if not found.
querySelectorAll(): selects all elements that match the specified CSS selector
HTML Structure:
<!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>
Select all elements that match the specified CSS selector:
const text = document.querySelectorAll(".text");
console.log(text);
Output:
Here, querySelectorAll(".text")
selects all elements with the class text
. It returns a NodeList (not an array, but array-like). If no elements are found, it logs an empty NodeList (NodeList []
).
Note on Live vs. Static Collections
- Methods like
getElementsByClassName()
andgetElementsByTagName()
return live HTMLCollections. This means if the DOM changes (elements added or removed), these collections automatically update to reflect the current state of the document. - In contrast,
querySelectorAll()
returns a static NodeList. This list does not update automatically if the DOM changes after the selection. To get updated results, you need to callquerySelectorAll()
again.
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
HTML Structure:
<!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>
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:
Here,
document.querySelector(".heading")
: Selects the first element with the classheading
and stores it inheading
.document.querySelector("img")
: Selects the first<img>
element in the document and stores it inimg
.heading.getAttribute("class")
: Retrieves the value of theclass
attribute from theheading
element.img.getAttribute("src")
: Retrieves the value of thesrc
attribute from theimg
element.console.log(className)
: Prints the class name(s) of the heading element.console.log(imgSrc)
: Prints the source URL/path of the image.
Note:
getAttribute()
returns the exact attribute value as written in HTML.- If the attribute doesn’t exist, it returns
null
.
hasAttribute(): returns true or false
HTML Structure:
<!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>
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:
Here,
document.querySelector("h1")
: Selects the first<h1>
element.document.querySelector("img")
: Selects the first<img>
element.heading.hasAttribute("class")
: Checks if the<h1>
element has aclass
attribute. Returnstrue
if it exists, otherwisefalse
.img.hasAttribute("src")
: Checks if the<img>
element has asrc
attribute. Returnstrue
orfalse
.
setAttribute(): sets the value of the specified attribute
HTML Structure:
<!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>
const img = document.querySelector("img");
//syntax for setAttribute:
//setAttribute(name,value);
img.setAttribute("alt", "picture");
const altText = img.getAttribute("alt");
console.log(altText);
Output:
Here,
img.setAttribute("alt", "picture")
: Sets (adds or updates) thealt
attribute of the<img>
element to "picture".img.getAttribute("alt")
: Retrieves the current value of thealt
attribute, which will now be "picture".console.log(altText)
: Prints "picture" to the console.
Note: setAttribute()
does not return a value, so if you store it inside a variable, it will be undefined
.
removeAttribute(): removes the specified attribute
HTML Structure:
<!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>
const img = document.querySelector("img");
img.removeAttribute("alt");
const altText = img.getAttribute("alt");
console.log(altText);
Output:
Here,
img.removeAttribute("alt")
: Removes thealt
attribute from the<img>
element.img.getAttribute("alt")
: Tries to get the value of thealt
attribute after removal.- Since the attribute was removed,
altText
will benull
. console.log(altText)
: Printsnull
because thealt
attribute no longer exists.
Note: removeAttribute()
doesn’t return a value, so if you store it inside a variable, it will be undefined
.
Modifying Classes of Selected Elements
The DOM provides the following methods to modify classes of selected elements.
classList.add(): adds a class
HTML Structure:
<!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>
const div = document.querySelector("div");
div.classList.add("active"); // Adds 'active' class
console.log(div);
Output:
classList.toggle(): toggles a class on or off
HTML Structure:
<!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>
const div = document.querySelector("div");
div.classList.toggle("active"); // Toggle a class named 'active' on the div
console.log(div.className); // Logs 'active' (if it was not present before)
Output:
classList.contains(): checks if class value exists
HTML Structure:
<!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>
const div = document.querySelector("div");
const containClass = div.classList.contains("active");
console.log(containClass);
Output:
classList.replace(): replaces the existing class value with a new class value
HTML Structure:
<!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>
const div = document.querySelector("div");
const replaceClass = div.classList.replace("active", "hidden");
console.log(div);
Output:
classList.remove(): remove a class value
HTML Structure:
<!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>
const div = document.querySelector("div");
const removeClass = div.classList.remove("box"); // removes the 'box' class
console.log(div);
Output:
Adding New Elements
HTML Structure:
<!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 in the document.
const newElement2 = document.createElement("p");
Now append this element inside the div
(newElement) created before.
newElement.appendChild(newElement2);
textContent
property is used to add 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.";
Output:
Removing Elements
HTML Structure:
<!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 the style
property.
HTML Structure:
<!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>
const heading = document.querySelector("h1");
heading.style.color = "red"; // This will change the color from black to red.
Output:
const button = document.querySelector("button");
button.style.backgroundColor = "green";
button.style.color = "white";
Output:
Similarly, you can change the other styles of the elements using the style
property.
Note: When modifying the style of elements using the DOM, always keep in mind to use the property names with camelCase. For example, instead of using font-size
, use fontSize
, and instead of background-color
, use backgroundColor
, etc.