Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 01, 2023 › #dynamically #HowTo

How to remove dynamically created div element in JavaScript

Today you will learn how to remove dynamically created div element using JavaScript.

Syntax #

To remove an div element, we can use the removeChild() method.

parentNode.removeChild(element)

So first, we will create a new div element using the createElement() method with an id and append it to a container.

Then, we will select the created div element using the getElementById() method and remove it from its parent element using the removeChild() method.

function createDiv(){
  const divContainer = document.createElement('div');
  divContainer.setAttribute('id', 'xyz');
  divContainer.innerText = 'New div element.';
  document.querySelector('.output').appendChild(divContainer);
}
function removeDiv(){
 const myDiv = document.getElementById('xyz');
 document.querySelector('.output').removeChild(myDiv);
}
save
listen
AI Answer
Write Your Answer
loading
back
View All