Introduction
JavaScript is an essential programming language that allows developers to create dynamic and interactive web pages. The DOM (Document Object Model) 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.
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);
The output will be as shown below:
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);
The output will be as shown below:
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);
The output will be as shown below:
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);
The output will be as shown below:
querySelectorAll()
selects all elements that match 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:
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:
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:
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:
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:
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:
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:
classList.contains()
checks if the 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:
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:
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:
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 in 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:
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 code:
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.
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 elements 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.
Keep coding!!
Click here to get a comprehensive javascript loop structure!
Check out toast.log, a browser extension that lets you see errors, warnings, and logs as they happen on your site — without having to open the browser’s console. Click here to get a 25% discount on toast.log.