This article will follow the below given steps of removing an element from a web page in JavaScript.
- getElementsById method
- remove() method
- removing child nodes or elements
What is getElementsById Method?
getElementsById, as the name suggests, is a JavaScript method that is used to retrieve a specific Id of an element and return it to a variable. This returned element value can be utilized in performing various tasks.
Syntax
Next, we’ll take a look at the built-in remove() method to find out how it can be used to remove elements by Id in Javascript.
The remove() Method in JavaScript
The remove() method in JavaScript helps in removing an element or a node. It does not take any parameters or returns any value.
As we have seen the purpose of both the getElementsByID method and the remove method. Now, we’ll take a look at a simple code snippet that will delete an HTML element from a web page:
HTML
In the above code snippet, a simple text is provided in <h1> and <h2> HTML element tag along with a button. Once the button is clicked the text inside the <h1> tag will be removed from the webpage.
Save and run the code, the output of the above snippet is similar to that shown below.
Now, a JavaScript code should be added behind the button so that when the button gets clicked, the desired results can be achieved.
JS
function myRemoveFunction() {
var textRemove = document.getElementById("mySelect");
textRemove.remove();
}
</script>
In the above script, it can be seen that a user-defined myRemoveFunction function has been created in which firstly the Id of the element is retrieved by the getElementById method and is stored in the variable textRemove.
After returning the element by Id to the variable textRemove, the built-in function of remove has been used which will remove the HTML element the moment the button is clicked.
On executing the above code, a similar output can be seen on the browser as presented below.
In the above snapshot of the output, it can be seen that, when the button is clicked, the text that was present in the <h1> Element tag has been removed from the web page.
Conclusion
JavaScript provides different methods for better web page functionality. The getElementById is one of the common and useful methods that returns an element’s Id value. The element whose Id is saved to a variable can be removed by using the built-in remove function of JavaScript.