JavaScript

How to Remove an HTML Element Using JavaScript?

JavaScript DOM manipulations allow a user to delete any element from the HTML webpage using the remove() method. However, a reference to its node is required in JavaScript to remove an element. Only with that reference can an element be removed from the webpage. The remove() method removes the HTML element from the document object model of the webpage by taking the element as a node. Let’s look at the syntax of the remove() method available to all HTML page elements.

Syntax of the remove() method

The syntax of the remove method is given as

elemRefference.remove();

From the syntax above, it is evident that you only need to apply the remove() on an element or on a node to remove it, and no additional parameters are required.

Example: Remove an element from an HTML webpage

To demonstrate the use of the remove() method, create an HTML webpage with some text and a button using the lines of code inside the <body> tag:

<center>
      <p id="myText">You want to remove me!</p>
      <br />
      <button onclick="buttonClicked()">Click me to remove</button>
</center>

Notice that an onclick() attribute has been added with the button that is going to look for the buttonClicked() method inside the script file. And the paragraph to remove has the id as “myText

Execute the HTML web page. You will see the following screen on your browser:

To add functionality on the button click, head over to the script file and create the buttonClicked() function with the following lines of code:

function buttonClicked() {
  // Upcoming lines are to be placed over inside here
}

Inside this function, the very first step is to get a reference to the paragraph to be removed by using the getElementById() method like

var elem = document.getElementById("myText");

The reference has been stored inside the elem variable. Use the remove() method on this elem variable with the help of the dot operator

elem.remove();

The whole script code snippet is will be like the following:

function buttonClicked() {
  var elem = document.getElementById("myText");
  elem.remove();
}

Execute the web page and click on the button to remove the paragraph tag with the id “myText”:

And the element has been removed from the HTML webpage and the DOM as well.

Conclusion

With every HTML element, there is a built-in function that comes with ES6 JavaScript that eradicates the element from the HTML webpage and the DOM. This method is named the remove() method and is applied to the element using a dot operator. The remove() method requires no arguments and does not return any value. This article demonstrated the working of the remove() method.

About the author

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor's degree in computer science.