January 05, 2025
Deleting HTML elements by using empty() and remove() jQuery methods
In jQuery, if we required to delete elements, we can use empty() or remove() methods. There is difference between these two methods. empty() method delete all the elements it contains and selector remains as undeleted (empty) and remove() method deletes selector element itself along with all the child elements. Example of empty() or remove() methods mentioned below:
empty() & remove() methods example
<html>
<head>
<title>Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="sourceElem">
Source Content
</div>
<br>
<button id="btnEmpty">Empty method example</button>
<button id="btnRemove">Remove method example</button>
<script>
$(document).ready(function () {
$('#btnEmpty').on('click', function () {
$("#sourceElem").empty();
});
$('#btnRemove').on('click', function () {
$("#sourceElem").remove();
});
});
</script>
</body>
</html>