To use jQuery to delete an element, the simplest way is to use the jQuery remove() method.
$("#div1").remove();
Let’s say I have the following HTML:
If we want to delete #div1 from the DOM, we can use the jQuery remove() method to do this with the following JavaScript code.
$("#div1").remove();
The resulting HTML would be as follows:
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1").remove()
Deleting an HTML Element Using jQuery With a Click
We can delete a specific HTML element using jQuery very easily by combining the remove() method with a click event.
Let’s say we have the following HTML code and we want to give the user the ability to delete the paragraph from the div.
This paragraph will not be deleted.
This is the paragraph we will delete.
Delete paragraph
Below is the JavaScript code which will allow the user to be able to delete the paragraph:
$("#click-me").click(function(){
$("#div1 p:nth-child(2)").remove();
});
We need to be careful when we are deleting elements from the DOM. We could have used the following code as well to delete the paragraph, but this would have also affected all the other paragraphs on the web page.
$("#click-me").click(function(){
$("p").remove();
});
In any case, we need to be careful with our selectors when using jQuery.
Finally, you will notice we use the jQuery :nth-child() selector. This is so we only target the second paragraph in the div, as we don’t want to delete the first paragraph.
The final code and output for this example of how to use jQuery to delete an element with a click is below:
Code Output:
This paragraph will not be deleted.
This is the paragraph we will delete.
Full Code:
This paragraph will not be deleted.
This is the paragraph we will delete.
Delete paragraph
Hopefully this article has been useful for you to understand how to use jQuery to delete an element.