How to clear content of div in JavaScript

How to clear content of div using JavaScript

Posted by Ervin Adams on August 5, 2022

How to clear content of div in JavaScript

How to clear content of div using JavaScript

Posted by Ervin Adams on August 5, 2022

Here is how you clear the contents of a div element on button click in JavaScript.

Step 1. Add onClick attribute with clearDiv() function to button

Step 2. Get the specified div element using document.getElementById()

Step 3. Clear the div element by using the innerHtml property

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wecode101 clear div element in JavaScript</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">
</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" onclick="clearDiv()">clear div</button>
        </div>
    </div>
  </main>
</body>
</html>

JS

function clearDiv() {
    document.getElementById('p-wrapper').innerHTML = "";
}