JavaScript DOM Manipulation
In this tutorial you will learn how to manipulate elements in JavaScript.
Manipulating DOM Elements in JavaScript
Now that you've learnt how to select and style HTML DOM elements. In this chapter we will learn how to add or remove DOM elements dynamically, get their contents, and so on.
Adding New Elements to DOM
You can explicitly create new element in an HTML document, using the document.createElement()
method. This method creates a new element, but it doesn't add it to the DOM; you'll have to do that in a separate step, as shown in the following example:
Example
Try this code »<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<script>
// Creating a new div element
let newDiv = document.createElement("div");
// Creating a text node
let newContent = document.createTextNode("Hi, how are you doing?");
// Adding the text node to the newly created div
newDiv.appendChild(newContent);
// Adding the newly created element and its content into the DOM
let currentDiv = document.getElementById("main");
document.body.appendChild(newDiv, currentDiv);
</script>
The appendChild()
method adds the new element at the end of any other children of a specified parent node. However, if you want to add the new element at the beginning of any other children you can use the insertBefore()
method, as shown in example below:
Example
Try this code »<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<script>
// Creating a new div element
let newDiv = document.createElement("div");
// Creating a text node
let newContent = document.createTextNode("Hi, how are you doing?");
// Adding the text node to the newly created div
newDiv.appendChild(newContent);
// Adding the newly created element and its content into the DOM
let currentDiv = document.getElementById("main");
document.body.insertBefore(newDiv, currentDiv);
</script>
Getting or Setting HTML Contents to DOM
You can also get or set the contents of the HTML elements easily with the innerHTML
property. This property sets or gets the HTML markup contained within the element i.e. content between its opening and closing tags. Checkout the following example to see how it works:
Example
Try this code »<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<script>
// Getting inner HTML conents
let contents = document.getElementById("main").innerHTML;
alert(contents); // Outputs inner html contents
// Setting inner HTML contents
let mainDiv = document.getElementById("main");
mainDiv.innerHTML = "<p>This is <em>newly inserted</em> paragraph.</p>";
</script>
As you can see how easily you can insert new elements into DOM using the innerHTML
property, but there is one problem, the innerHTML
property replaces all existing content of an element. So if you want to insert the HTML into the document without replacing the existing contents of an element, you can use the insertAdjacentHTML()
method.
This method accepts two parameters: the position in which to insert and the HTML text to insert. The position must be one of the following values: "beforebegin"
, "afterbegin"
, "beforeend"
, and "afterend"
. This method is supported in all major browsers.
The following example shows the visualization of position names and how it works.
Example
Try this code »<!-- beforebegin -->
<div id="main">
<!-- afterbegin -->
<h1 id="title">Hello World!</h1>
<!-- beforeend -->
</div>
<!-- afterend -->
<script>
// Selecting target element
let mainDiv = document.getElementById("main");
// Inserting HTML just before the element itself, as a previous sibling
mainDiv.insertAdjacentHTML('beforebegin', '<p>This is paragraph one.</p>');
// Inserting HTML just inside the element, before its first child
mainDiv.insertAdjacentHTML('afterbegin', '<p>This is paragraph two.</p>');
// Inserting HTML just inside the element, after its last child
mainDiv.insertAdjacentHTML('beforeend', '<p>This is paragraph three.</p>');
// Inserting HTML just after the element itself, as a next sibling
mainDiv.insertAdjacentHTML('afterend', '<p>This is paragraph four.</p>');
</script>
Note: The beforebegin
and afterend
positions work only if the node is in the DOM tree and has a parent element. Also, when inserting HTML into a page, be careful not to use user input that hasn't been escaped, to prevent XSS attacks.
Removing Existing Elements from DOM
Similarly, you can use the removeChild()
method to remove a child node from the DOM. This method also returns the removed node. Here's an example:
Example
Try this code »<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<script>
let parentElem = document.getElementById("main");
let childElem = document.getElementById("hint");
parentElem.removeChild(childElem);
</script>
It is also possible to remove the child element without exactly knowing the parent element. Simply find the child element and use the parentNode
property to find its parent element. This property returns the parent of the specified node in the DOM tree. Here's an example:
Example
Try this code »<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<script>
let childElem = document.getElementById("hint");
childElem.parentNode.removeChild(childElem);
</script>
Replacing Existing Elements in DOM
You can also replace an element in HTML DOM with another using the replaceChild()
method. This method accepts two parameters: the node to insert and the node to be replaced. It has the syntax like parentNode.replaceChild(newChild, oldChild);
. Here's an example:
Example
Try this code »<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<script>
let parentElem = document.getElementById("main");
let oldPara = document.getElementById("hint");
// Creating new elememt
let newPara = document.createElement("p");
let newContent = document.createTextNode("This is a new paragraph.");
newPara.appendChild(newContent);
// Replacing old paragraph with newly created paragraph
parentElem.replaceChild(newPara, oldPara);
</script>