How do I clear the content of a div using JavaScript?

JavascriptHtmlCss

Javascript Problem Overview


When the user clicks a button on my page, the content of a div should be cleared. How would I go about accomplishing this?

Javascript Solutions


Solution 1 - Javascript

Just Javascript (as requested)

Add this function somewhere on your page (preferably in the <head>)

function clearBox(elementID)
{
    document.getElementById(elementID).innerHTML = "";
}

Then add the button on click event:

<button onclick="clearBox('cart_item')" />

In JQuery (for reference)

If you prefer JQuery you could do:

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

Solution 2 - Javascript

You can do it the DOM way as well:

var div = document.getElementById('cart_item');
while(div.firstChild){
	div.removeChild(div.firstChild);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRajasekarView Question on Stackoverflow
Solution 1 - JavascriptTom GullenView Answer on Stackoverflow
Solution 2 - JavascriptMicView Answer on Stackoverflow