Home >Web Front-end >CSS Tutorial >How Can I Clear a Div\'s Content with JavaScript on Button Click?

How Can I Clear a Div\'s Content with JavaScript on Button Click?

Susan Sarandon
Susan SarandonOriginal
2024-11-27 08:31:15352browse

How Can I Clear a Div's Content with JavaScript on Button Click?

Clearing Div Content with JavaScript

To remove the content from a div when a user clicks a button, follow these steps:

Creating the Clear Function

  1. Define a JavaScript function to clear the div's content, typically within the section:
function clearBox(elementID) {
    document.getElementById(elementID).innerHTML = "";
}

Connecting the Button

  1. Add an onclick event to the button that will trigger the clear function:
<button onclick="clearBox('div_id')">Clear Div</button>

Replace div_id with the actual ID of the div you want to clear.

jQuery Example (Optional)

  1. For those using jQuery, an alternative method exists:
$('#div_id').html("");

By following these steps, you can easily clear the content of a div when a button is clicked, allowing for dynamic interaction with your web page.

The above is the detailed content of How Can I Clear a Div\'s Content with JavaScript on Button Click?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn