[javascript] 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()">

This question is related to javascript html innerhtml

The answer is


Another solution is to use getDocumentById and insertAdjacentHTML.

Code:

function addRow() {

 const  div = document.getElementById('content');

 div.insertAdjacentHTML('afterbegin', 'PUT_HTML_HERE');

}

Check here, for more details: Element.insertAdjacentHTML()


To remove node you can try this solution it helped me.

var rslt = (nodee=document.getElementById(id)).parentNode.removeChild(nodee);

To my most biggest surprise I present to you a DOM method I've never used before googeling this question and finding ancient insertAdjacentHTML on MDN (see CanIUse?insertAdjacentHTML for a pretty green compatibility table).

So using it you would write

_x000D_
_x000D_
function addRow () {_x000D_
  document.querySelector('#content').insertAdjacentHTML(_x000D_
    'afterbegin',_x000D_
    `<div class="row">_x000D_
      <input type="text" name="name" value="" />_x000D_
      <input type="text" name="value" value="" />_x000D_
      <label><input type="checkbox" name="check" value="1" />Checked?</label>_x000D_
      <input type="button" value="-" onclick="removeRow(this)">_x000D_
    </div>`      _x000D_
  )_x000D_
}_x000D_
_x000D_
function removeRow (input) {_x000D_
  input.parentNode.remove()_x000D_
}
_x000D_
<input type="button" value="+" onclick="addRow()">_x000D_
_x000D_
<div id="content">_x000D_
</div>
_x000D_
_x000D_
_x000D_


Add HTML inside div using JavaScript

Syntax:

element.innerHTML += "additional HTML code"

or

element.innerHTML = element.innerHTML + "additional HTML code"

Remove HTML inside div using JavaScript

elementChild.remove();

<!DOCTYPE html>
<html>
<head>
    <title>Dynamical Add/Remove Text Box</title>
    <script language="javascript">

        localStorage.i = Number(1);

        function myevent(action)
        {
            var i = Number(localStorage.i);
            var div = document.createElement('div');

            if(action.id == "add")
            {
                localStorage.i = Number(localStorage.i) + Number(1);
                var id = i;
                div.id = id;
                div.innerHTML = 'TextBox_'+id+': <input type="text" name="tbox_'+id+'"/>' + ' <input type="button" id='+id+' onclick="myevent(this)" value="Delete" />';

                document.getElementById('AddDel').appendChild(div);
            }
            else
            {
                var element = document.getElementById(action.id);
                element.parentNode.removeChild(element);
            }
        }
    </script>
</head>
<body>
    <fieldset>
    <legend>Dynamical Add / Remove Text Box</legend>
    <form>
        <div id="AddDel">
            Default TextBox:
            <input type="text" name="default_tb">
            <input type="button" id="add" onclick="myevent(this)" value="Add" />
        </div>
            <input type="button" type="submit" value="Submit Data" />
    </form>
    </fieldset>
</body>
</html>

make a class for that button lets say :

`<input type="button" value="+" class="b1" onclick="addRow()">`

your js should look like this :

$(document).ready(function(){
  $('.b1').click(function(){
      $('div').append('<input type="text"..etc ');
  });
});

please try following to generate

 function addRow()
    {
        var e1 = document.createElement("input");
        e1.type = "text";
        e1.name = "name1";

        var cont = document.getElementById("content")
        cont.appendChild(e1);

    }

You can use this function to add an child to a DOM element.

function addElement(parentId, elementTag, elementId, html) 

 {


// Adds an element to the document


    var p = document.getElementById(parentId);
    var newElement = document.createElement(elementTag);
    newElement.setAttribute('id', elementId);
    newElement.innerHTML = html;
    p.appendChild(newElement);
}



function removeElement(elementId) 

{

    // Removes an element from the document
    var element = document.getElementById(elementId);
    element.parentNode.removeChild(element);
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to innerhtml

React.js: Set innerHTML vs dangerouslySetInnerHTML Angular 2 - innerHTML styling How do I clear inner HTML Show/hide 'div' using JavaScript How to get the innerHTML of selectable jquery element? Cannot set property 'innerHTML' of null Add/remove HTML inside div using JavaScript Javascript - Replace html using innerHTML Add inline style using Javascript It says that TypeError: document.getElementById(...) is null