Removing and Detaching Elements
In this page:
remove()
The remove() method deletes the selected element completely, along with its children, text, and any attached data or event handlers. Once removed, the element is gone from the DOM and its jQuery data can't be recovered.
Example: remove()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">To remove</div>
<script>
$("#box").remove();
</script>
</body>
</html>
empty()
empty() removes the contents of the selected element -- its child nodes and text -- but keeps the element itself in the DOM. This is useful for clearing out a container, like a search results list, before filling it with new content.
Example: empty()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul id="results"><li>Old 1</li><li>Old 2</li></ul>
<script>
$("#results").empty();
</script>
</body>
</html>
detach()
detach() removes an element from the DOM while keeping its jQuery data and event handlers intact in memory. This makes it the right choice when you plan to reinsert the same element later and don't want to lose its bound behavior.
Example: detach()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Detach me</div>
<script>
const saved = $("#box").detach();
// saved can be reinserted later with its data/handlers intact
</script>
</body>
</html>
Remove by Selector
You can pass a selector to remove() to delete only the matching elements out of a larger selection, rather than every element you've selected. This lets you filter what gets deleted without writing a separate selection first.
Example: Remove by Selector
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul id="list"><li class="done">Task 1</li><li>Task 2</li></ul>
<script>
$("#list li").remove(".done");
</script>
</body>
</html>
Remove or Empty
Use remove() when the element itself should disappear entirely from the page. Use empty() when only its contents should disappear but the container itself needs to stay in place, ready to be filled again.
Example: Remove or Empty
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="container"><p>Old content</p></div>
<script>
$("#container").empty();
// use remove() instead if the container itself should also disappear
</script>
</body>
</html>
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: