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

Add and remove div using JavaScript

In this article, you will learn how to add a div element using JavaScript and how to remove a dynamically created div element with a button click.

To add a div element, we will use the insertAdjacentHTML() method which takes two values, position, and HTML code.

Syntax. #

document.querySelector('div').insertAdjacentHTML('afterbegin','HTML Code')

To remove the created div element we will use the remove() method.

For this, we have a basic HTML structure as you can see below.

<input type="text" id="ex-input" placeholder="Enter your name">
<input type="button" value="+" onclick="addRow()">
<div id="ex-con"></div>

Now what we need to do is we will create the function addRow() and inside that function, we will select the div element and insert the below code using the insertAdjacentHTML() method.

<div class="ex-row">
   <div>Name Section</div>
   <input type="button" value="-" onclick="removeRow(this)">
</div>

Final project

<input type="text" id="ex-input" placeholder="Enter your name">
<input type="button" value="+" onclick="addRow()">
<div id="ex-con"></div>
<script>
function addRow() {
  document.querySelector('#ex-con').insertAdjacentHTML(
    'afterbegin',
    `<div class="ex-row">
       <div>${document.querySelector('#ex-input').value}</div>
       <input type="button" value="-" onclick="removeRow(this)">
    </div>`      
  )
}

function removeRow(input) {
  input.parentNode.remove()
}
</script>
save
listen
AI Answer
Write Your Answer
loading
back
View All