Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a `HierarchyRequestError` when I repeat adding a new element Inside a 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>
like image 590
Ed Pudol Avatar asked Feb 21 '14 14:02

Ed Pudol


2 Answers

You are trying to append an element inside itself. JavaScript won't let you do that.

like image 92
StephenRios Avatar answered Sep 28 '22 20:09

StephenRios


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

like image 40
Suman Bogati Avatar answered Sep 28 '22 20:09

Suman Bogati