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()

Before moving further, we’ve prepared a video tutorial to remove elements from a web page using jQuery:

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:

<!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 remove() Method

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:

<!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

jQuery empty() Method

jQuery - Add Element
jQuery - Add CSS Class
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment