JS DOM Manipulation

Manipulating DOM Elements in JavaScript

Now that you've learned how to select and style HTML DOM elements, let's explore how to dynamically add or remove DOM elements, retrieve their contents, and more.

Adding New Elements to the DOM

To create a new element in an HTML document, you can use the document.createElement() method. This method creates a new element but does not immediately add it to the DOM. You'll need to perform that step separately, as demonstrated in the following example:

<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 
var newDiv = document.createElement("div");

// Creating a text node 
var 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 
var currentDiv = document.getElementById("main"); 
document.body.appendChild(newDiv, currentDiv);
</script>

The appendChild() method adds the new element at the end of the children of a specified parent node. Alternatively, if you want to add the new element at the beginning of the children, you can use the insertBefore() method, as demonstrated in the example below:

<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 
var newDiv = document.createElement("div");

// Creating a text node 
var 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 
var currentDiv = document.getElementById("main"); 
document.body.insertBefore(newDiv, currentDiv);
</script>

Getting or Setting HTML Contents to DOM

You can retrieve or change the contents of HTML elements effortlessly using the innerHTML property. This property allows you to set or get the HTML markup that resides within the element, which includes the content between its opening and closing tags. Check out the example below to see how it functions:

<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>

<script>
// Getting inner HTML conents
var contents = document.getElementById("main").innerHTML;
alert(contents); // Outputs inner html contents

// Setting inner HTML contents
var mainDiv = document.getElementById("main");
mainDiv.innerHTML = "<p>This is <em>newly inserted</em> paragraph.</p>";
</script>

While the innerHTML property makes it easy to insert new elements into the DOM, it does have a limitation: it replaces all existing content within an element. To insert HTML into a document without replacing existing content, you can use the insertAdjacentHTML() method.

This method takes two parameters: the position at which to insert and the HTML text to insert. The position must be one of the following values: "beforebegin", "afterbegin", "beforeend", or "afterend". This method is supported in all major browsers.

The following example illustrates the positioning options and how they function:

<!-- beforebegin -->
<div id="main">
<!-- afterbegin -->
<h1 id="title">Hello World!</h1>
<!-- beforeend -->
</div>
<!-- afterend -->

<script>
// Selecting target element
var 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 only function if the node is part of the DOM tree and has a parent element. Additionally, when inserting HTML into a page, it's important to avoid using unescaped user input to prevent XSS (Cross-Site Scripting) attacks.


Removing Existing Elements from DOM

Similarly, you can utilize the removeChild() method to remove a child node from the DOM. This method returns the removed node as well. Here's an example:

<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>

<script>
var parentElem = document.getElementById("main");
var childElem = document.getElementById("hint");
parentElem.removeChild(childElem);
</script>

It's also possible to remove a child element without knowing its exact parent element. You can locate the child element and then use the parentNode property to access its parent element. This property retrieves the parent of the specified node in the DOM tree. Here's an example:

<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>

<script>
var childElem = document.getElementById("hint");
childElem.parentNode.removeChild(childElem);
</script>

Replacing Existing Elements in DOM

You can replace an element in the HTML DOM with another using the replaceChild() method. This method takes two parameters: the new node to insert and the existing node to replace. It follows this syntax: parentNode.replaceChild(newChild, oldChild);. Here's an example:

<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>

<script>
var parentElem = document.getElementById("main");
var oldPara = document.getElementById("hint");

// Creating new elememt
var newPara = document.createElement("p");
var newContent = document.createTextNode("This is a new paragraph.");
newPara.appendChild(newContent);

// Replacing old paragraph with newly created paragraph
parentElem.replaceChild(newPara, oldPara);
</script>