Consider the code below. It works the first time, but not on following presses of the button. I am getting the following error message:
Uncaught HierarchyRequestError: Failed to execute 'appendChild' on 'Node': The new child element contains the parent.
function addElement() {
var txt='<input type="text" name="school[]"> '+
'<input type="text" name="degree[]">'+
'<input type="text" name="gradYear[]">';
var ni = document.getElementById('school');
ni.innerHTML = txt;
ni.appendChild(ni);
}
<input type="button" name="add" value="Add School" onClick="addElement()">
<div id="school">
</div>
You are trying to append an element inside itself. JavaScript won't let you do that.
This is wrong ni.appendChild(ni);
, you can not do the self append. You can append the tag inside it's parent. Here how we can append the input tag inside it's parent.
function addElement() {
var ni = document.getElementById('school');
var firstInput = createInput('school');
ni.appendChild(firstInput);
var seconInput = createInput('degree');
ni.appendChild(seconInput);
var thirdInput = createInput('gradYear');
ni.appendChild(thirdInput);
}
function createInput(name){
var input = document.createElement('input'); // creating the input
input.setAttribute('type', 'text'); // setting the type attribute
input.setAttribute('name', name+'[]');
return input;
}
The working DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With