abhillier
abhillier

Reputation: 214

Appending a div element using javascript

I am new to jQuery and I am practicing appending div elements. Here is my code:

<!doctype html>
<html lang="en">
<head>
    <title>Div Id</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>

<script>
    document.body.onload = addElement;

    function addElement () { 
        // create a new div element 
        // and give it some content 
        var newDiv = document.createElement("div"); 
        var newContent = document.createTextNode("This is a first division"); 
        newDiv.appendChild(newContent); //add the text node to the newly created div. 

        // add the newly created element and its content into the DOM 
        var currentDiv = document.getElementById("div1"); 
        document.body.insertBefore(newDiv, currentDiv); 
    }
</script>

<body>
    <div id="div1">This is a second division.</div>
</body>
</html>

Output would be:

This is a second division.

But as per my implementation the output should be

This is a first division
This is a second division.

I am not able to figure where it is going wrong. Please someone help me out with this.

Thanks in advance.

Upvotes: 0

Views: 177

Answers (4)

Quentin
Quentin

Reputation: 944564

onload is a property of the window object, not the document.body object.

This works:

window.onload = addElement;

Upvotes: 1

Alberto
Alberto

Reputation: 1863

If you want to use jQuery you can check this fiddle:

$('body').prepend('<div>This is a first division</div>');

Upvotes: 0

guradio
guradio

Reputation: 15565

$('#div1').before('<div id=div0>This is a first division</div>')

demo

If you want Jquery it is as simple as this.

Upvotes: 0

FalcoB
FalcoB

Reputation: 1333

actually it works.... try to move your javascript in the head of you html file

document.body.onload = addElement;

function addElement () { 
  // create a new div element 
  // and give it some content 
  var newDiv = document.createElement("div"); 
  var newContent = document.createTextNode("This is a first division"); 
  newDiv.appendChild(newContent); //add the text node to the newly created div. 

  // add the newly created element and its content into the DOM 
  var currentDiv = document.getElementById("div1"); 
  document.body.insertBefore(newDiv, currentDiv); 
}
<div id="div1">This is a second division.</div>

Upvotes: 1

Related Questions