In web programming developers often face situations where it is required to remove either the entire HTML element or only the elements nested within a specified element. To accomplish these tasks with great ease there are certain jQuery methods available such as remove() and empty(). This write-up will guide you on how to use these methods to remove an HTML element with the help of relevant examples.
Remove an HTML element using jQuery
Apply the below-mentioned methods to remove elements in jQuery.
Here we have discussed the above-mentioned methods in-depth.
remove() Method
This method removes an HTML element and everything inside it, which includes any content, or elements nested within the specified element.
Example
Suppose you want to remove a <div> element including all the nested elements present inside it using the remove() method. Use the following code.
HTML
In the above HTML code, we have created a <div>, and inside that <div> we have nested a <p> element. Moreover, we have also created a button that will remove the <div> element.
jQuery
Now we have applied the remove() method that will remove the entire <div> and all of its child elements.
Output
The remove() method has successfully removed the whole div.
empty() Method
The empty() method is also used for removing elements, however, this method only removes the content or the elements nested inside the specified element.
Example
To demonstrate the working of the empty() method, we are using the above example but now instead of applying the remove() method we will apply the empty() method.
jQuery
In the above code, the empty() method is used that will remove only the content or elements nested inside the div.
Output
The nested elements inside the div have been removed successfully.
Conclusion
HTML elements can be removed using the two methods provided by jQuery which are; remove(), and empty(). The remove() method removes an HTML element and everything inside it, which includes any content, or elements nested within the specified element, meanwhile, the empty() method only removes the content or the elements nested inside the specified element. These methods are highlighted in detail in this guide, along with relevant examples.