Sathishkumar Sathishkumar - 9 days ago 5
HTML Question

How to create div element on page load in javascript?

I want to create div element on page load event, i write some code, but its not working correclty?

function createfn(){
//debugger;
var element = document.createElement("div");
var para = document.createTextNode('The man who mistook his wife for a hat');
element.appendChild(para);
document.getElementByTagName(body).appendChild(element);

}
window.onload=createfn();


Where im wrong in this code?

Answer

a few issues:

first the tag name body needs to be wrapped in quotes. in your code you are passing an undeclared variable called body.

Secondly, its getElementsByTagName() asthis function returns multiple elements in an array.

Lastly, you need to target the first body element:

    function createfn(){
    //debugger;
    var element = document.createElement("div");
    var para = document.createTextNode('The man who mistook his wife for a hat');
    element.appendChild(para);
    document.getElementsByTagName('body')[0].appendChild(element);

    }
    window.onload=createfn();

jsfiddle