0

I'm trying to add button inside the div the div element when i'm click to a button. The following JS code:

function doThis(){
    var btn= document.createElement("input");
    btn.type="submit";
    btn.value="button";
    var child=document.getElementById("child");
    var submit=document.getElementById("submit");
    child.insertAfter(btn, submit);
}

and html markup:

<div id="parent" class="parent">
    <div id="child" class="child">
        <input type="text" class="text"/>
        <input id="submit" type="submit" onclick="doThis()"/>
    </div>
<div>

In console i have error message: Uncaught TypeError: Object #<HTMLDivElement> has no method insertAftert. How to fix this?JSFIDDLE

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • 1
    you can use `child.appendChild(btn);` http://jsfiddle.net/BYwz9/2/ –  Dec 13 '13 at 10:59

1 Answers1

1

There's no insertAfter, use insertBefore instead.

 submit.parentNode.insertBefore(btn, submit.nextSibling);

if submit is the last Child, then submit.nextSibling is null, and insertBefore will just append it to the parentNode.

http://jsfiddle.net/rooseve/BYwz9/1/

Andrew
  • 5,290
  • 1
  • 19
  • 22