remove element/content
To remove elements and content, you can generally use the following two jQuery methods:
- remove() - removes the selected element (and its children)
- empty() - removes child elements from the selected element
jQuery remove() method
The jQuery remove() method removes the selected element and its children.
<script> $(document).ready(function(){ $("button").click(function(){ $("#div1").remove(); }); }); </script> </head> <body> <div id="div1" style="height:40px;width:300px;border:1px solid black;background-color:yellow;"> Your dreams will fade away with your age</p></div> <button>Remove div element</button>
jQuery empty() method
The jQuery empty() method removes the children of the selected element.
$(document).ready(function(){ $("button").click(function(){ $("#div1").empty(); }); }); </script> </head> <body> <div id="div1" style="height:40px;width:300px;border:1px solid black;background-color:yellow;"> The best dream is to meet the best of you</div> <button>Empty div element</button>
filter deleted elements
The jQuery remove() method also accepts an argument that allows you to filter on the removed elements.
This parameter can be any jQuery selector syntax.
The following example removes all <p> elements with class="italic":
$(document).ready(function(){ $("button").click(function(){ $("p").remove(".italic"); }); }); </script> </head> <body> <p>This is a paragraph. </p> <p class="italic"><i>This is another paragraph. </i></p> <p class="italic"><i>This is another paragraph. </i></p> <button>Remove all p elements with class="italic". </button>