Syntax of the remove() method
The syntax of the remove method is given as
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:
<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:
// 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
The reference has been stored inside the elem variable. Use the remove() method on this elem variable with the help of the dot operator
The whole script code snippet is will be like the following:
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.