How to add or remove HTML inside div using JavaScript?

Spread the love

To add or remove HTML inside div using JavaScript, we call the appendChild and removeChild methods.

For instance, we write

const addRow = () => {
  const div = document.createElement("div");

  div.className = "row";

  div.innerHTML = `
    <input type="text" name="name" value="" />
    <input type="text" name="value" value="" />
      <input type="checkbox" name="check" value="1" /> Checked? 
    <input type="button" value="-" onclick="removeRow(this)" />


const removeRow = (input) => {

to define the addRow and removeRow functions.

In addRow, we create a div with createElement.

We set innerHTML to set it to a string with the content for the div.

Then we call appendChild to append the div as the last child of the element with ID content.

In removeRow, we call removeChild to remove the input element’s parent node with removeChild.

Leave a Reply

Your email address will not be published. Required fields are marked *