When the user clicks a button on my page, the content of a div should be cleared. How would I go about accomplishing this?
Asked
Active
Viewed 6.8e+01k times
152
-
[This question is being discussed on meta.](https://meta.stackoverflow.com/questions/370942/is-this-question-considered-on-topic) – Script47 Jul 12 '18 at 11:35
2 Answers
270
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("");

animuson
- 53,861
- 28
- 137
- 147

Tom Gullen
- 61,249
- 84
- 283
- 456
-
50
-
-
@Tom Gullen this worked for me without passing the id of the DIV into the function, and with single quotes around the elementID in the function itself. Thanks for this! – DPSSpatial Jul 09 '14 at 17:28
-
3@Tom Gullen : please not that this does'nt remove event handlers associated with the nodes inside that div. – bhavya_w Sep 15 '14 at 11:40
-
**@Mic**'s answer is about 250x quicker. https://jsperf.com/innerhtml-vs-removechild – tleb Oct 24 '16 at 00:45
-
-
108
You can do it the DOM way as well:
var div = document.getElementById('cart_item');
while(div.firstChild){
div.removeChild(div.firstChild);
}

Mic
- 24,812
- 9
- 57
- 70
-
1Top notch! The same as jQuery: $("#cart_item").empty(); acting on DOM and not only on content. Great! – Pedro Ferreira Mar 27 '16 at 00:59
-
-
The DOM way was(at the time of the answer) and is probably still today much faster than `innerHTML` – Mic May 24 '16 at 19:53
-
1this feels cleaner than `innerHTML = ''`. I would personally write the extra couple of lines – dmo Nov 04 '16 at 14:40
-
-
1@Sukima this way is faster than prefered answer, so if you need better performance rather than short code this is your choose. – iiic Feb 06 '18 at 08:16
-
1as a one liner `while(div.firstChild && div.removeChild(div.firstChild));` – Russell Elfenbein Apr 24 '18 at 12:48
-
@RussellElfenbein, that one-liner is missing getting the div element. – Jānis Elmeris Jun 01 '18 at 11:01