jQuery empty()
0 1550
This jQuery method is used to remove all content inside the selected element including all child elements and their content but the selected element does not removed by this method.
Note:
If you only want to remove the selected element without removing its child elements and event handlers form the web page then use detach() jQuery method.
Related Topics:
jQuery clone
jQuery appendTo
Note:
If you want to remove the selected element with its child elements and event handlers form the web page then use remove() jQuery method.
jQuery empty
Syntax:
$(selector).empty();
Example:
In this example we remove all paragraphs and headings within the <div> tag.
<html>
<head>
<title>jQuery Example</title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
.para{
background:yellow;
padding:10px;
}
.head{
background:pink;
padding:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").empty();
$text="<h3> All elements are removed</h3>";
$("div").prepend($text);
});
});
</script>
</head>
<body>
<h2>jQuery empty() method Example</h2>
<div>
<h3 class="head">This is heading 1</h3>
<h3 class="head">This is heading 1</h3>
<h3 class="head">This is heading 1</h3>
<p class="para">This paragraph 1.</p>
<p class="para">This paragraph 2.</p>
<p class="para">This paragraph 3.</p>
</div>
<button>Click me!</button>
</body>
</html>
Output:
When you click the button,
Share:
Comments
Waiting for your comments