jQuery Remove
The remove()
method in jQuery allows you to remove selected elements from the DOM. This method ensures that both the element and its associated data and events are removed completely.
Key Topics
Basic Usage of remove()
The remove()
method removes the selected element(s) from the DOM.
$("#element").remove();
Explanation: This code removes the element with the ID element
from the DOM.
Removing with Filtering
The remove()
method can also take a filter parameter to remove only matching elements.
$("li").remove(".completed");
Explanation: This code removes only the <li>
elements with the class completed
from the DOM.
Example: Using remove()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Remove Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<ul>
<li class="task">Task 1</li>
<li class="task completed">Task 2</li>
<li class="task">Task 3</li>
</ul>
<button id="removeButton">Remove Completed</button>
<script>
$(document).ready(function() {
$("#removeButton").click(function() {
$("li").remove(".completed");
});
});
</script>
</body>
</html>
Explanation: This example uses the remove()
method to delete only the completed tasks (with the class completed
) when the button is clicked.
Key Takeaways
- Complete Removal: Use
remove()
to delete elements, including their data and event handlers. - Selective Removal: Apply filtering to remove specific elements from a group.
- Dynamic DOM Updates: Simplify DOM management by removing unnecessary elements in response to user actions.