Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
How to remove all the elements from DOM using element ID in jQuery?
To remove all the elements from DOM using element ID, use the remove() method. The remove() method in jQuery removes the selected element and all of its child elements from the DOM completely.
Syntax
The basic syntax for removing elements by ID is ?
$("#elementID").remove();
Where elementID is the ID of the element you want to remove along with all its child elements.
Example
You can try to run the following code to remove all the elements from DOM using element ID ?
$(document).ready(function(){
$("button").click(function(){
$("#mydiv").remove();
alert("Element with ID 'mydiv' has been removed!");
});
});
// HTML structure
var htmlContent = `
<button>Click to remove all elements</button><br>
<div id="mydiv" style="height:200px;width:350px;border:2px solid red;background-color:blue;">
<p>This is some text.</p>
<span>This is demo text.</span>
</div>
`;
console.log("Before removal - Element exists:", $("#mydiv").length > 0);
$("#mydiv").remove();
console.log("After removal - Element exists:", $("#mydiv").length > 0);
The output of the above code is ?
Before removal - Element exists: true After removal - Element exists: false
In this example, when you click the button, the entire div element with ID "mydiv" is removed from the DOM, including all its child elements (the paragraph and span tags). Once removed, the element cannot be accessed or manipulated further unless you re-create it.
Complete HTML Example
Here's a complete HTML page demonstrating the remove functionality ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#mydiv").remove();
});
});
</script>
</head>
<body>
<button>Click to remove all elements</button><br>
<div id="mydiv" style="height:200px;width:350px;border:2px solid red;background-color:blue;">
<p>This is some text.</p>
<span>This is demo text.</span>
</div>
</body>
</html>
Conclusion
The jQuery remove() method provides a simple and effective way to completely remove DOM elements by their ID, along with all child elements and associated data.
