Removing Elements and Content with jQuery
jQuery provides two main methods to remove elements or just their inner content from the DOM:
- remove() – Completely removes the selected element along with all of its child elements.
- empty() – Clears only the inner content, leaving the selected element itself intact.
jQuery remove() Method
The remove() method deletes the selected element(s) entirely from the page, including all of their children.
Example – Using remove():
$("#div1").remove();
In this example, the element with ID div1 and everything inside it will be completely removed from the DOM.
jQuery empty() Method – Clear Content Without Removing the Element
The empty() method in jQuery is used to remove all child elements and content from the selected element(s), while keeping the parent element itself in the DOM.
Example – Using empty():
$("#div1").empty();
In this example, the element with ID div1 will remain on the page, but all of its inner content—including any text or child elements—will be completely removed.
This is useful when you want to clear out an element without deleting it entirely.
Filtering Elements with jQuery remove()
The jQuery remove() method isn't limited to removing all matched elements — it can also accept a selector parameter to filter which elements should be removed.
This allows you to precisely target and remove only specific elements based on classes, IDs, or other jQuery selector patterns.
Example 1 – Remove <p> Elements with Class .test
$("p").remove(".test");
This will remove only the <p> elements that have the class test, leaving other paragraphs unaffected.
Example 2 – Remove <p> Elements with Class .test or .demo
$("p").remove(".test, .demo");
This removes all <p> elements that have either the test class, the demo class, or both.
Using selector-based filtering with remove() helps you clean up specific elements without affecting the entire DOM structure.