
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.
- Below we have the basic HTML structure.
<button onclick="addRow()">+</button> <div id="ex-container"> </div>
- 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)" />
-
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); }
- Finally, we have to create the removeRow() function as well.
function removeRow(input) { document.getElementById('ex-container').removeChild(input.parentNode); }
save
listen
AI Answer
Add/remove HTML inside div using JavaScript
0
In this article, we will write a program that adds HTML elements to a div element and rem…
asked
Apu
0 answers
2915
In this article, we will write a program that adds HTML elements to a div element and rem…
Answer Link
answered
Apu