Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add/remove HTML inside div using JavaScript

I want to be able to add multiple rows to a div and also removing them. I have a '+' button at the top of the page which is for adding content. Then to the right of every row there is a '-' button that's for removing that very row. I just can't figure out the javascript code in this example.

This is my basic HTML structure:

<input type="button" value="+" onclick="addRow()">  <div id="content">  </div> 

This is what I want to add inside the content div:

<input type="text" name="name" value="" /> <input type="text" name="value" value="" /> <label><input type="checkbox" name="check" value="1" />Checked?</label> <input type="button" value="-" onclick="removeRow()"> 
like image 818
Daniel Tovesson Avatar asked Jul 15 '13 09:07

Daniel Tovesson


People also ask

Can you delete HTML element in JavaScript?

Given an HTML element and the task is to remove the HTML element from the document using JavaScript. Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.

What is the correct way to append a link inside a div object in JavaScript?

HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code ('afterbegin', 'beforebegin', 'afterend', 'beforeend')

How add and remove items in JavaScript?

The list items are added or removed using JavaScript functions addItem() and removeItem(). The list items are created using document. createElement() method and to create a text node, document. createTextNode() method is used and then this node is appended using appendChild() method.

How do you add or remove elements in HTML?

In your JavaScript program, you can use the “appendChild()” and “insertBefore()” methods for adding the HTML elements and to delete the HTML elements “remove()” and the “removeChild()” methods are invoked.


1 Answers

You can do something like this.

function addRow() {   const div = document.createElement('div');    div.className = 'row';    div.innerHTML = `     <input type="text" name="name" value="" />     <input type="text" name="value" value="" />     <label>        <input type="checkbox" name="check" value="1" /> Checked?      </label>     <input type="button" value="-" onclick="removeRow(this)" />   `;    document.getElementById('content').appendChild(div); }  function removeRow(input) {   document.getElementById('content').removeChild(input.parentNode); } 
like image 123
Austin Brunkhorst Avatar answered Oct 09 '22 09:10

Austin Brunkhorst