Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
When we are coding web pages and applications, we need some way to change the structure of documents. For this, we manipulate DOM (Document Object Model), which is a set of API for controlling HTML and styling information. There are many ways to do DOM Manipulation in Javascript. But we only need to know some basic DOM manipulation techniques to get a clear idea about it.
The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web.
JavaScript DOM manipulation refers to the process of using JavaScript to interact with and modify the Document Object Model (DOM) of a web page. The DOM is a hierarchical representation of a web page’s structure, consisting of elements like paragraphs, headings, links, images, and more. By manipulating the DOM, developers can dynamically change the content, structure, and style of a web page in response to user interactions or other events.
Different Methods to Manipulate DOM
The Document Object Model (DOM) provides a structured representation of a web page, allowing developers to interact with and manipulate its elements programmatically. Various methods enable selecting, modifying, creating, and styling DOM elements, enhancing dynamic web functionality and user experience.
1. DOM Element Selectors
DOM element selectors are methods used to select and access specific elements in the DOM tree. Common selectors include getElementById, getElementsByClassName, and querySelector, allowing developers to target single or multiple elements for further manipulation. For example, document.getElementById("myElement") selects an element with the ID "myElement", enabling operations like modification or event handling.
2. DOM Content Manipulators
DOM content manipulators are methods that modify the content of selected elements. Key methods include innerHTML, textContent, and appendChild. These methods allow developers to change the text or HTML inside an element, add new child elements, or remove existing ones. For instance, setting element.innerHTML = "<p>New content</p>" replaces the existing content of the element with new HTML.
3. DOM Element Creators
DOM element creators are methods that allow developers to create new elements dynamically. The primary method used is createElement, which generates an element of a specified type (e.g., div, span). Once created, these elements can be customized and inserted into the DOM using methods like appendChild or insertBefore. For example, let newDiv = document.createElement("div"); creates a new <div> element.
4. DOM CSS Manipulators
DOM CSS manipulators enable developers to change the styles of elements dynamically. Methods such as style.property, classList.add, classList.remove, and setAttribute allow for modifying inline styles, adding or removing CSS classes, and setting attributes like style directly. For example, element.style.color = "red"; changes the text color of the selected element to red.
HTML documents can be created using the document.createElement() method.
Creating an Element
The document.createElement() method can be used to create the HTML element specified by tagName.
Code:
const body = document.body
const div = document.createElement("div") // tag name is “div” here
div.textContent = "HELLO 2"
body.append(div)
Adding Elements to the Page
New elements in an HTML document can be created using the document.createElement() method.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DOM Manipulation in Javascript</title>
</head>
<body>
<div id="main">
<h1 id="title">Coding Ninjas!</h1>
<p id="hi">Hi!</p>
</div>
<button type="button" onclick="insertElement()">Click Here!</button>
<script>
function insertElement() {
// Creating a new div element
var newDiv = document.createElement("div");
// Creating a text node
var newContent = document.createTextNode("How are you?");
// Adding the text node to the newly created div
newDiv.appendChild(newContent);
// Adding the newly created element and its content into the DOM
var currentDiv = document.getElementById("main");
document.body.appendChild(newDiv, currentDiv);
}
</script>
</body>
</html>
Output
Adding new elements at the end of any other children of a specific parent node can be done with the help of appendChild(). New elements can be added at the beginning of any other children using the insertBefore() method.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DOM Manipulation in Javascript</title>
</head>
<body>
<div id="main">
<h1 id="title">Coding Ninjas!</h1>
<p id="hi">Hi!</p>
</div>
<button type="button" onclick="insertElement()">Insert Element</button>
<script>
function insertElement() {
// Creating a new div element
var newDiv = document.createElement("div");
// Creating a text node
var newContent = document.createTextNode("How are you?");
// Adding the text node to the newly created div
newDiv.appendChild(newContent);
// Adding the newly created element and its content into the DOM
var currentDiv = document.getElementById("main");
document.body.insertBefore(newDiv, currentDiv);
}
</script>
</body>
</html>
Output
Get and set element
The innerHTML property can be used to get or set the contents of the HTML element.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DOM Manipulation in Javascript</title>
</head>
<body>
<div id="test">
<h1 id="title">Ninja!</h1>
<p id="hi">Hello.</p>
</div>
<button type="button" onclick="getContents()">Get Contents</button>
<button type="button" onclick="setContents()">Set Contents</button>
<script>
function getContents() {
// Getting inner HTML contents
var contents = document.getElementById("test").innerHTML;
alert(contents); // Outputs inner html contents
}
function setContents() {
// Setting inner HTML contents
var mainDiv = document.getElementById("test");
mainDiv.innerHTML = "<p>This paragraph was inserted using the setContents().</p>";
}
</script>
</body>
</html>
Output
Modifying HTML Elements
We can do DOM Manipulation in Javascript using the "innerHTML" property. It sets the inner HTML content within the element.The only disadvantage of innerHTML() is that it replaces the existing content of an element. Let us see an example:-
Code:
<!DOCTYPE html>
<html>
<body>
<p id="demo" onclick="changeInnerHTML()">Click on me to change my inner HTML content.</p>
<script>
function changeInnerHTML() {
document.getElementById("demo").innerHTML = "I have changed!";
}
</script>
</body>
</html>
Output
In order to not replace the existing contents we useinsertAdjacentHTML() method. This method contains two methods, one is the position to insert, and the other is the HTML text to insert.
Code:
<!DOCTYPE html>
<html>
<body>
<p>insertAdjacentHTML() demo</p>
<h2 id="myHeading">Javascript</h2>
<p>Javascript is the programming language of the web.</p>
<button onclick="myFunction()">Click here to get more info</button>
<script>
function myFunction() {
var insert = document.getElementById("myHeading");
insert.insertAdjacentHTML("afterend", "<p>Javascript is easy to learn</p>");
}
</script>
</body>
</html>
Output
Removing Elements
To remove elements in an HTML document we can use the removeChild() method.
For removing an element, the HTML code is:
<!DOCTYPE html>
<html lang="en">
<head>
<title>DOM Manipulation in Javascript</title>
<script src="script.js" defer></script>
</head>
<body>
<div id="root">
<p id="title">Hello Ninjas!</p>
<p id="test">This is a simple paragraph for you.</p>
</div>
<!-- We can remove an element by using removeChild() method. The script code is as follows -->
<script>
var parentElem = document.getElementById("root");
var childElem = document.getElementById("test");
parentElem.removeChild(childElem);
</script>
</body>
</html>
Output:
Replacing Existing Elements in DOM
The replaceChild() method can be used to replace elements in the HTML DOM with other elements.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DOM Manipulation in Javascript</title>
</head>
<body>
<div id="main">
<h1 id="title">Hi!</h1>
<p id="test">This text will change if you click the button!.</p>
</div>
<button type="button" onclick="replaceParagraph()">REPLACE</button>
<script>
function replaceParagraph() {
var parentElem = document.getElementById("main");
var oldPara = document.getElementById("test");
// Creating new element
var newPara = document.createElement("p");
var newContent = document.createTextNode("The text has got changed!");
newPara.appendChild(newContent);
// Replacing old paragraph with newly created paragraph
parentElem.replaceChild(newPara, oldPara);
}
</script>
</body>
</html>
Yes, JavaScript can be used to modify the HTML DOM, allowing developers to change content, attributes, and styles dynamically.
Can DOM be manipulated only using JavaScript?
No, while JavaScript is the most common way to manipulate the DOM, other languages like jQuery and frameworks like React can also perform DOM manipulations.
How does DOM represent the documents?
The DOM represents the document as nodes and objects
What are DOM elements?
A DOM element is something like a DIV, HTML, BODY element on a page. You can add classes to all of these using CSS or interact with them using JS.
What is the use of insertBefore() method?
The insertBefore() method will insert a node as a child, right before an existing child, which you specify.
Conclusion
DOM (Document Object Model) is a set of API for controlling HTML and styling information. The methods discussed in the blog give us a basic understanding of DOM Manipulation in Javascript, which helps to modify HTML pages' data dynamically. Here, we learned how to create an element, add and modify elements, remove an element, etc.
If you loved reading this article about DOM Manipulation in Javascript, check out Free JavaScript Tutorial By Code360 and 20 Projects With JavaScript Code Examples.