Vidro3 Vidro3 - 1 month ago 15
Javascript Question

Javascript remove DOM element if exists

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.

Answer

Your code has multiple issues.

function clearDOM() {
  if (div.document.body) {
    let removeDiv = document.getElementsByTagName("div");
    document.body.removeChild(removeDiv);
  }
};

First, indent your code properly. Also, functions do not need a terminating semi-colon.

Anyway, in the above, div.document.body does not mean anything; div is an undefined variable. What are you trying to check for? Remove this if condition.

Second, getElementsByTagName returns a list of nodes, and you can't removeChild that directly. You'll have to loop:

let removeDivs = document.getElementsByTagName("div");
for (let i=0; i<removeDivs.length; i++) document.body.removeChild(removeDivs[i]);

Although it will not affect the way your code works, it is better practice to create all the new elements in advance and insert them all at once, using DocumentFragment.

function appendStuff(data) {
  let frag = document.createDocumentFragment();

  for ( let i = 0; i < data.length; i++ ) {
    let div = document.createElement('div');
    let id = document.createElement('h1');
    div.appendChild(id);
    frag.appendChild(div);
  }

  document.body.appendChild(frag);
}

By the way, you don't need to use querySelector to get the body. It's right there in document.body.