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

How Can I Clear a Div\'s Content Using JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-11-30 18:52:16321browse

How Can I Clear a Div's Content Using JavaScript?

Clearing Div Content with JavaScript

To dynamically remove the content of a div element when a user clicks a button, JavaScript offers an efficient solution.

Answer:

Using Pure JavaScript:

  1. Define a function to clear the content of a div:
function clearBox(elementID) {
    document.getElementById(elementID).innerHTML = "";
}
  1. Add an onclick event listener to the button that triggers the clearBox function:
<button onclick="clearBox('cart_item')">Clear Div</button>

Using jQuery (for comparison):

$("#cart_item").html("");

The above is the detailed content of How Can I Clear a Div\'s Content Using JavaScript?. 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