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>
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>
Share
Improve this question
edited Apr 15, 2015 at 4:26
Alex
13.2k34 silver badges62 bronze badges
asked Feb 21, 2014 at 14:48
Ed PudolEd Pudol
971 gold badge1 silver badge3 bronze badges
3
|
3 Answers
Reset to default 10You 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
You can either set the innerHTML, or you can use ni.appendChild() to add HTML DOM Nodes. Choose one or the other, not both.
The error is because you tried to do ni.appendChild(ni), for which the message should be obvious.
ni.appendChild(ni);
wtf? – Danilo Valente Commented Feb 21, 2014 at 14:49ni.innerHTML
you've technically already added the HTML children, then you're trying to again with append child, but appending it to itself. You can leave it with just .innerHTML or more appropriately create a new node (not named ni), and append it to "ni". – nerdwaller Commented Feb 21, 2014 at 14:51