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

Add/remove HTML inside div using JavaScript

In this article, we will write a program that adds HTML elements to a div element and removes those elements after clicking a button.

Before we start the details, please take a look at its final demo.

Add or remove HTML inside div using JavaScript.

In the steps below, we have explained how to create the above project.

  1. Below we have the basic HTML structure.
    <button onclick="addRow()">+</button>
    <div id="ex-container">
      
    </div>
  2. Now, this is what we want to add inside the above div element.
     <input type="text" name="name" placeholder="Your name" />
     <label> 
       <input type="checkbox" name="check" value="1" /> Complete 
     </label>
     <input type="button" value="-" onclick="removeRow(this)" />
      
  3. Now, we have created the function addRow(). Inside the function, we have created a new div element using the createElement() method, using the className property set a class to the created div element, and using the innerHTML property added the above code inside the div element. Finally, append the created div element inside the main container as a child.

    function addRow(){
      const div = document.createElement('div');
    
      div.className = 'ex-row';
    
      div.innerHTML = `
       <input type="text" name="name" placeholder="Your name" />
        <label> 
          <input type="checkbox" name="check" value="1" /> Complete 
        </label>
        <input type="button" value="-" onclick="removeRow(this)" />
      `;
    
      document.getElementById('ex-container').appendChild(div);
    }
  4. Finally, we have to create the removeRow() function as well.
    function removeRow(input) {
      document.getElementById('ex-container').removeChild(input.parentNode);
    }
save
listen
AI Answer
Write Your Answer
loading
back
View All