0

I'm trying to insert a button into my html using javascript, I read this tutorial : javascript.info/tutorial/modifying-document and made this simple example to test it : jsfiddle.net/XuAfA/86/ but it's not working ... Here is the code of the example if you don't want to open the url :

var bibi = document.getElementById('bibi');
var s = document.createElement('button');
s.innerHTML = "toto";
document.insertBefore(s, bibi);

and my html :

    <ul id="Parent">
       <button id="bibi"> hello wrold ! </button>
    </ul>

I can't see why this is not working

2 Answers 2

1

insertBefore is executed on the parent element of the element you want to insert before

parent.insertBefore(toInsert, child);

As the document contains the body which contains the elements etc. you can't use document as the parent element, you should be doing

bibi.parentNode.insertBefore(s, bibi);

FIDDLE

Sign up to request clarification or add additional context in comments.

Comments

0

Next code explains the difference between INNERHTML and CREATE ELEMENT to add a button :

<html>
  <head>
    <title>Insert element</title>
    <script type="text/javascript">

function btn_inner () {
var bibi = document.getElementById( 'bibi' );
bibi.innerHTML = "<input type='button' value='I was created with INNERHTML ! ! !' />";
}

function btn_create () {
var bibi = document.getElementById( 'bibi' );
var obj;
obj = document.createElement( "input" );
obj.type  = "button";
obj.value = "I was created with CREATE ELEMENT ! ! !";
bibi.appendChild( obj );
}

    </script>
  </head>
  <body>
    <button onclick="btn_inner()">Click here to insert button with INNERHTML</button>
    <button onclick="btn_create()">Click here to insert button with CREATE ELEMENT</button>
    <br/>
    <br/>
    <div id="bibi"></div>
  </body>
</html>

Create a textfile, rename it TEST.HTML (or any name), then copy-paste previous code, save the file and double click it to open it in a browser.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.