JavaScript

HTML Elements Manipulation through JavaScript

DOM is an acronym for Document Object Model, and it can be simply described as a browser-generated tree of nodes. JavaScript can be utilized for manipulating the methods and properties of each added node or HTML element. Manipulating HTML elements is also considered the most useful feature of JavaScript.

This write-up will discuss manipulating HTML Elements through JavaScript. We will also explain the procedure for adding HTML Elements, appending HTML Elements, Changing content of HTML Elements, finding and getting HTML Elements, and removing HTML Elements and their child nodes. Moreover, the examples related to appendChild(), insertBefore(), innerHTML property, getElementById(), getElementbyClassName(), querySelectorAll(), remove(), and removeChild() methods will be provided. So, let’s start!

How to add HTML Elements through JavaScript using appendChild() method

The JavaScript appendChild() method is utilized for adding an HTML element as the child of the specified parent node. This method is used to move HTML elements.

Syntax of appendChild() method

parentNode.appendChild(childNode);

Here, the parentNode is the HTML element we want to declare as a parent, whereas the childNode is the newly created HTML element added to the parent node.

Example: How to add HTML Elements through JavaScript using appendChild() method

In this example, we will show you how to use the “appendChild()” method for adding the HTML elements through JavaScript. First of all, we will add a heading and a paragraph using the <h2>and <p>HTML elements:

<!DOCTYPE html>

<html>

<body>


<h2>This is linuxhint.com</h2>

<p>Adding HTML Elements through JavaScript.</p>


<div id="div1">

<p id="p1">This is the main paragraph.</p>

<p id="p2">This is second paragraph.</p>

</div>

In the next step, we will create a new <p>element “paragraph” by utilizing the “createElement()” method of the document object:

<script>

const paragraph = document.createElement("p");

At this point, we have only created a <p>; however, we have not added any text node to it. To do so, we have to create a text node:

const node = document.createTextNode("This is new node.");

Then, we will append the created text node “node” to our “paragraph” element, and we will find an existing element:

paragraph.appendChild(node);

const element = document.getElementById("div1");

Lastly, we will append the “paragraph” element to the existing HTML “element”:

element.appendChild(paragraph);

</script>

</body>

</html>

Execute the above-given program in your favorite code editor or any online coding sandbox; however, we will utilize the JSBin for this purpose:

As you can see from the below-given output, a new HTML element is added having the text content “This is new node”:

How to append HTML Elements through JavaScript using insertBefore() method

If you want to append an HTML element as a child node before the specified node, you can invoke the “insertBefore()” JavaScript method.

Syntax of insertMethod() method

parentNode.insertBefore(newNode, existingNode);

Here, the “newNode” is the newly created HTML element that you want to add, “existingNode” is the element before which you will insert your HTML element, and the “parentNode” is the HTML element that you have specified as the parent node.

Example: How to append HTML Elements through JavaScript using insertBefore() method

In the previous example, we have utilized the appendChild() method for adding the new HTML element as the last child of the parent HTML. However, you can also use the JavaScript “insertBefore()” method to add an HTML element before the specified element. The below-given example will teach you the usage of “insertBefore()” method.

Firstly, we will add a heading and some paragraphs as follows:

<!DOCTYPE html>

<html>

<body>


<h2>This is linuxhint.com</h2>

<p>Adding HTML Elements through JavaScript.</p>


<div id="div1">

<p id="p1">This is the main paragraph.</p>

<p id="p2">This is second paragraph.</p>

</div>

Next, we will create a new element “paragraph” HTML element, and then define a child text node for it:

<script>

const paragraph = document.createElement("p");

const node = document.createTextNode("This is new node.");

paragraph.appendChild(node);

const element = document.getElementById("div1");

Now, we will specify “p1” as child element, so that we can insert the created “paragraph” element before it:

const child = document.getElementById("p1");

Lastly, we will pass the HTML element “paragraph” and “child” element to the insertBefore() method:

element.insertBefore(paragraph,child);

</script>

</body>

</html>

Execution of the above-given program will add the “paragraph” HTML before “p1”:

How change content of HTML Elements through JavaScript using innerHTML property

The HTML DOM permits you to change the HTML content by utilizing the “innerHTML” property. The “innerHTML” is typically used in web pages to generate dynamic HTML content such as comment forms, registration forms, and links.

Syntax of innerHTML JavaScript property

element.innerHTML = value

Here, “element” is the HTML element you have selected to change its content, and “value” is the content we will set.

Example 1: Changing content of HTML Elements through JavaScript

This example will show you how to use the “innerHTML” JavaScript property to modify an HTML element’s content. Firstly, we will add a heading element with the <h2>heading tag and a paragraph with the <p>HTML tag:

<!DOCTYPE html>

<html>

<body>


<h2>Change HTML Elements using JavaScript</h2>


<p id="p1">A test string</p>

Now, we want to change the content of the “<p>” element having the id “p1”. To do so, we will utilize the “document.getElementById()” method to get the specified element. After that, we will set the content of our <p>element to “This is linuxhint.com”:

<script>

document.getElementById("p1").innerHTML = "This is linuxhint.com";

</script>


<p>We have changed the content of the above paragraph</p>


</body>

</html>

Check out the below-given output, which we got from executing the above-given program:

How to Find and Get HTML elements by Id through JavaScript

Most of the JavaScript developers utilized the getElementById() method for finding and getting HTML elements having unique ids. If you have passed an id that does not belong to any HTML element, the getElementById() method will display the null value.

Syntax of getElementById() method

document.getElementById(elementId)

Here, the “elementId” represents the unique ID of the HTML element which you want to find and get in your JavaScript code.

Example: Find and Get HTML elements by Id through JavaScript

In the following example, we will add HTML elements such as a heading with the <h2>tag and three paragraph elements with the <p>tag. Note that we have also added “ids” with the paragraph elements:

<!DOCTYPE html>

<html>

<body>


<h2>This is linuxhint.com</h2>


<p id="p1">Find and Get HTML elements by Id in JavaScript</p>

<p>This is a JavaScript program that utilizes the "getElementsById" method</p>


<p id="p2"></p>

In the next step, we will find and get the element having the id “p1” by using the “document.getElementById()” method. After ding so, we will change the content of the retrieved HTML element:

<script>

const element = document.getElementById("p1");

document.getElementById("p2").innerHTML =

"The text of the first paragraph is: " + element.innerHTML;


</script>


</body>

</html>

How to Find and Get HTML elements by ClassName through JavaScript

The “getElementsByClassName()” method is used for finding and getting HTML elements having the same class. When you try to get an HTML element by utilizing the class name, the JavaScript interpreter will return all objects belonging to the same class. After that, you can perform specific operations on those HTML elements.

Syntax of getElementsByClassName() method

document.getElementsByClassName(className)

Here, the “className” represents the class name of the HTML elements which you are required to find and get in your program.

Example: Find and Get HTML elements by ClassName through JavaScript

In the following example, we have added a heading and some paragraph elements with the className “c1”:

<!DOCTYPE html>

<html>

<body>


<h2>This is linuxhint.com</h2>


<p>Find and Get HTML elements by Class Name in JavaScript</p>

<p class="c1">text in first paragrpah</p>

<p class="c1">text in second paragraph</p>


<p id="p1"></p>

Next, we will search for the HTML elements which have “c1” as their class by using the getElementsByClassName() method and will store the collections of the objects in “a”:

<script>

const a = document.getElementsByClassName("c1");

After finding and getting the required HTML elements, we will show the content of the first object present at the first index:

document.getElementById("p1").innerHTML =

'The first paragraph (index 0) with class="c1" is: ' + a[0].innerHTML;

</script>

</body>

</html>

Here is the output which we got from executing the above-given JavaScript program:

How to Find and Get HTML elements by CSS selector through JavaScript

In HTML, the querySelectorAll() method returns a static NodeList object that comprises a collection of the child elements of an element matched with the specified CSS selectors. Index numbers are used to find and get the nodes, starting at 0.

Syntax of querySelectorAll() method

element.querySelectorAll(selectors)

The querySelectorAll() method takes “selectors” as an argument; a DOM string comprises one or more valid CSS selectors.

Example: Find and Get HTML elements by CSS selector through JavaScript

In the below-given JavaScript program, we have used the querySelectorAll() method to find and get the paragraph HTML elements having “c1” as their class name:

<!DOCTYPE html>

<html>

<body>


<h2>This is linuxhint.com</h2>


<p>Find and Get HTML elements by Class Name in JavaScript</p>

<p class="c1">text in first paragrpah</p>

<p class="c1">text in second paragraph</p>


<p id="p1"></p>


<script>

const a = document.querySelectorAll("p.c1");

document.getElementById("p1").innerHTML =

'The first paragraph with class="c1" is: ' + a[0].innerHTML;

</script>


</body>

</html>

Check out the output of the JavaScript querySelectorAll() method:

Execution of the above-given JavaScript program will show the following output:

How to remove HTML Elements through JavaScript using remove() method

The JavaScript “remove()” method is used for deleting the specified HTML element from the Document Object Model (DOM).

Syntax of remove() method

node.remove()

Here, “node” represents the HTML element you want to delete through JavaScript.

Example: Remove HTML Elements through JavaScript using remove() method

In the below-given, we have add a heading HTML element, a paragraph <p>and a <div>element which comprises two paragraphs <p1>and <p2>as child nodes:

<!DOCTYPE html>

<html>

<body>


<h2>This is linuxhint.com</h2>

<p>Adding HTML Elements through JavaScript.</p>


<div id="div1">

<p id="p1">This is the main paragraph.</p>

<p id="p2">This is second paragraph.</p>

</div>

Next, we will add a button and attach an “onclick” event handler. According to the following code, when we will click on the “Remove Element” button, it will invoke the “myFunction()” method:

<button onclick="myFunction()">Remove Element</button>

In the “myFunction()” method, firstly, we utilize the “document.getElementbyId” to find the element which we want to delete by specifying its “id”, then we will invoke the “remove()” method:

<script>

function myFunction() {

document.getElementById("p1").remove();

}

</script>


</body>

</html>

The below-given output signifies that “p1” HTML is deleted from our JavaScript program with the help of the “remove()” function:

How to remove child HTML Elements through JavaScript using removeChild() method

In JavaScript, the “removeChild()” is utilized for deleting a specific child HTML node from an HTML element.

Syntax of removeChild() method

parentNode.removChild(childNode)

Here, the parentNode is the HTML element we have specified as a “parent” node, and ChildNode is the HTML element we want to remove from the parent element.

Remove child HTML Elements through JavaScript using removeChild() method

In this example, we will try to remove the child element of our defined <div>HTML element:

<!DOCTYPE html>

<html>

<body>


<h2>This is linuxhint.com</h2>

<p>Adding HTML Elements through JavaScript.</p>


<div id="div1">

<p id="p1">This is the main paragraph.</p>

<p id="p2">This is second paragraph.</p>

</div>

To delete a child element, first of all, you have to create a “parent” HTML element and specify the HTML element acting as a parent in your JavaScript code. In our case, we have added “div1”:

<script>

const parent = document.getElementById("div1");

Next, we will define a “child” element and will get the child Element which we want to delete from the parent HTML element:

const child = document.getElementById("p1");

To invoke the removeChild() method, we will utilize the “parent” element and then pass the “child” element as an argument to the removeChild() method:

parent.removeChild(child);

</script>

</body>

</html>

As you can see that the <p1> child element of the <div1> HTML element is deleted successfully:

Conclusion

The Document Object Model (DOM) in JavaScript is an developer interface that permits you to manipulate the design, structure, and content of your website’s HTML elements. This write-up discussed manipulating HTML Elements through JavaScript. We have also explained the procedure for adding HTML Elements, appending HTML Elements, Changing content of HTML Elements, finding and getting HTML Elements, and removing HTML Elements and their child nodes. Moreover, the examples related to appendChild(), insertBefore(), innerHTML property, getElementById(), getElementsbyClassName(), querySelectorAll(), remove(), and removeChild() methods are also provided.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.