I have a button with an event listener that appends items to the DOM when clicked. I'd like to add a function that clears those appended elements on subsequent button clicks.
Here's what I've tried but keep getting "div is undefined".
function appendStuff(data) {
for ( let i = 0; i < data.length; i++ ) {
let body = document.querySelector('body');
let div = document.createElement('div');
let id = document.createElement('h1');
div.appendChild(id)
body.appendChild(div)
}
};
button.addEventListener('click', (event) => {
clearDOM(), appendStuff()
});
function clearDOM() {
if (div.document.body) {
let removeDiv = document.getElementsByTagName("div");
document.body.removeChild(removeDiv);
}
};
I suppose a work-around would be to disable the button after a single click.
I think the catch here is that the first time the button is clicked there will not be a div element in the DOM. That seems to be what is throwing the error. Was hoping the If statement would get around that.