27 Jan jQuery – Remove Element
In this lesson, we will learn how to remove elements from a web page using jQuery. Let us see the jQuery methods to remove content:
- remove()
- empty()
jQuery remove() method
The remove() method in jQuery is used to remove the selected element and its child elements. In the below example, we will remove the <p> element:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn").click(function(){ $("p").remove(); }); }); </script> <style> p { height:150px; width:500px; border:1px solid black; background:blue; color: white; } </style> </head> <body> <h1>Demo Heading</h1> <p>We will remove this line.</p> <p>We will remove this line as well. Click the below button to remove both the lines.</p> <button id="btn">Remove</button> </body> </html> |
Output
jQuery empty() method
The empty() method in jQuery is used to remove the child elements and content. It takes elements out of the DOM but will not remove the element. In the below example, we will remove the content of the <p> element but <p> will not get removed:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn").click(function(){ $("p").empty(); }); }); </script> <style> p { height:150px; width:500px; border:1px solid black; background:blue; color: white; } </style> </head> <body> <h1>Demo Heading</h1> <p>We will remove this line (only the line).</p> <p>We will remove this line as well (only the line). Click the below button to remove only the lines.</p> <button id="btn">Remove</button> </body> </html> |
Output
No Comments