Wednesday 27 April 2022

jQuery - Remove Elements

 With jQuery, it is easy to remove existing HTML elements.


Remove Elements/Content

To remove elements and content, there are mainly two jQuery methods:

  • remove() - Removes the selected element (and its child elements)
  • empty() - Removes the child elements from the selected element

jQuery remove() Method

The jQuery remove() method removes the selected element(s) and its child elements.

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script>

$(document).ready(function(){

  $("button").click(function(){

    $("#div1").remove();

  });

});

</script>

</head>

<body>


<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">


This is some text in the div.

<p>This is a paragraph in the div.</p>

<p>This is another paragraph in the div.</p>


</div>

<br>


<button>Remove div element</button>


</body>

</html>


jQuery empty() Method

The jQuery empty() method removes the child elements of the selected element(s).

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").empty();
  });
});
</script>
</head>
<body>

<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">

This is some text in the div.
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>

</div>
<br>

<button>Empty the div element</button>

</body>
</html>

No comments:

Post a Comment