The empty() method removes all child nodes and content from the selected elements.
Try it Yourself - Copy paste code in Online HTML Editor to see the result
Description
Remove all child nodes of the set of matched elements from the DOM.
Syntax
.empty()
$(selector).empty() This method does not accept any arguments.
Examples
Example 1
Removes all child nodes (including text nodes) from all paragraphs
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>empty demo</title>
<style>
p {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
<p>
Hello, <span>Person</span> <em>and person</em>.
</p>
<button>Call empty() on above paragraph</button>
<script>
$("button").click(function() {
$("p").empty();
});
</script>
</body>
</html>
Example 2
Remove the content of all
elements:
Try it Yourself - Copy paste code in Online HTML Editor to see the result
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("div").empty();
});
});
</script>
</head>
<body>
<div style="height:100px;background-color:yellow">
This is some text
<p>This is a paragraph inside the div.</p>
</div>
<p>This is a paragraph outside the div.</p>
<button>Remove content of the div element</button>
</body>
</html>
Comments
Post a Comment