How to remove div content in Jquery

How to remove div content using Jquery

Posted by Luke Beeno on August 5, 2022

How to remove div content in Jquery

How to remove div content using Jquery

Posted by Luke Beeno on August 5, 2022

Here is how you clear a div element on button click in Jquery.

Step 1. Add onclick listener event to button by using selector $("#id")

Step 2. Get the specified div field by using selector $("#id")

Step 3. Clear the div by using the html() method

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wecode101 clear div element in Jquery</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
  <main>
    <!--Main layout-->
    <div class="container">
        <div class="col-9 pt-5 mx-auto">
            <div id="p-wrapper">
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
                <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque</p>
                <p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis</p>
                <p>On the other hand, we denounce with righteous indignation and dislike men</p>
            </div>
            <button type="button" class="btn btn-primary" id="clear-div">clear div</button>
        </div>
    </div>
  </main>
</body>
</html>

JS

$( "#clear-div" ).click(function() {
    $("#p-wrapper").html('');
});