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
-
Economics & Finance
Selected Reading
How can I remove everything inside of a using jQuery?
To remove everything inside a div element, you can use jQuery's empty() method or remove() method. The empty() method removes all child elements while keeping the div itself, whereas remove() removes the entire div element including its contents.
Using empty() Method
The empty() method is the most appropriate choice when you want to clear the contents inside a div while preserving the div element itself ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".btn-empty").click(function(){
$("div#demo").empty();
});
});
</script>
</head>
<body>
<button class="btn-empty">Clear contents inside div</button>
<div id="demo">
<p>Inside div - This is demo text.</p>
<p>Inside div - This is demo text.</p>
</div>
<span>
<p>Inside span - This is demo text.</p>
<p>Inside span - This is demo text.</p>
</span>
</body>
</html>
Using remove() Method
The remove() method removes the entire div element along with all its contents ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".btn-remove").click(function(){
$("div#demo").remove();
});
});
</script>
</head>
<body>
<button class="btn-remove">Remove entire div</button>
<div id="demo">
<p>Inside div - This is demo text.</p>
<p>Inside div - This is demo text.</p>
</div>
<span>
<p>Inside span - This is demo text.</p>
<p>Inside span - This is demo text.</p>
</span>
</body>
</html>
Key Differences
The main difference between these methods is ?
- empty() ? Removes only the child elements, keeping the div container intact
- remove() ? Removes the entire div element from the DOM
Conclusion
Use empty() when you want to clear the contents inside a div while preserving the container, and use remove() when you want to completely remove the div element from your webpage.
Advertisements
