Search code examples
javascripthtmladditioninnerhtml

JS - Insert element on the <div> tag


I need to add a tag with some Elements, but the innerHTML inserts before appendChild. My Js function:

function addFields(){
    var isbn_container = document.getElementById("isbn_container");
    isbn_container.innerHTML += "<div>";
    var div = document.createElement("div");
    var input = document.createElement("input");
    input.type = "text";
    input.name = "new-isbn-10[]";
    isbn_container.appendChild(input);

    var input2 = document.createElement("input");
    input2.type = "text";
    input2.name = "new-isbn-13[]";
    isbn_container.appendChild(input2);
    isbn_container.innerHTML += "<span onclick='deleted(this);'> delete</span>";
    isbn_container.appendChild(document.createElement("br"));
    isbn_container.appendChild(document.createElement("br"));
    isbn_container.after.innerHTML += "</div>";
}

The result:

<div></div>
<input type="text" name="new-isbn-10[]">
<input type="text" name="new-isbn-13[]">
<span onclick="deleted(this);"> delete</span>
<br><br>

But I want:

<div>
<input type="text" name="new-isbn-10[]">
<input type="text" name="new-isbn-13[]">
<span onclick="deleted(this);"> delete</span>
<br><br>
</div>

Help me please.


Solution

  • In your code:

    function addFields(){
        var isbn_container = document.getElementById("isbn_container");
        isbn_container.innerHTML += "<div>";
    

    Don't do that, it's invalid markup and completely unnecessary given the following line:

        var div = document.createElement("div");
        var input = document.createElement("input");
        input.type = "text";
        input.name = "new-isbn-10[]";
        isbn_container.appendChild(input);
    

    You want this inside the div, so don't do that, add it to the div:

        div.appendChild(input);
    

    Same here:

        var input2 = document.createElement("input");
        input2.type = "text";
        input2.name = "new-isbn-13[]";
        isbn_container.appendChild(input2);
    

    Replace with:

        div.appendChild(input2);
    

    Again, adding stuff to isbn_container doesn't put it in the div, so don't do this:

        isbn_container.innerHTML += "<span onclick='deleted(this);'> delete</span>";
        isbn_container.appendChild(document.createElement("br"));
        isbn_container.appendChild(document.createElement("br"));
    

    Do this:

        div.innerHTML += "<span onclick='deleted(this);'> delete</span>";
        div.appendChild(document.createElement("br"));
        div.appendChild(document.createElement("br"));
    

    Now all that stuff is in the div, so you can now add the div to the document:

        isbn_container.appendChild(div);
    }