Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Creating an Element
3.
Adding Elements to the Page
4.
Get and set element
5.
Modifying HTML Elements
6.
Removing Elements
7.
Replacing Existing Elements in DOM
8.
Frequently Asked Questions
9.
Key Takeaways
Last Updated: Sep 9, 2024

DOM Manipulation in Javascript

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.

 

The basic code of our HTML structure :-

<!DOCTYPE html>
<html lang="en">
<head>
<title>DOM Manipulation in Javascript</title>
</head>
<body> </body>
</html>
You can also try this code with Online Javascript Compiler
Run Code

Also Read, Javascript hasOwnProperty

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)
You can also try this code with Online Javascript Compiler
Run Code

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>
You can also try this code with Online Javascript Compiler
Run Code

 

 

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>
You can also try this code with Online Javascript Compiler
Run Code

 

 

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>
You can also try this code with Online Javascript Compiler
Run Code

 

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> 
You can also try this code with Online Javascript Compiler
Run Code

 

Output

 

In order to not replace the existing contents we use insertAdjacentHTML() 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>
You can also try this code with Online Javascript Compiler
Run Code

 

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>
You can also try this code with Online Javascript Compiler
Run Code

 

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>
You can also try this code with Online Javascript Compiler
Run Code

 

Output

 

Practice it by yourself with the help of an online javascript compiler.

Must Read Fibonacci Series in JavaScript

Frequently Asked Questions

  1. How does DOM represent the documents?

The DOM represents the document as nodes and objects

 

2. 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.

 

3. 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.

Key Takeaways

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 Coding Ninjas and 20 Projects With JavaScript Code Examples.

Live masterclass