html - How to create div element on page load in JavaScript using createElement function? - Stack Overflow

I want to create a div element on page load event but my script is not working as expected.function cr

I want to create a div element on page load event but my script is not working as expected.

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();

What is it wrong with this code?

I want to create a div element on page load event but my script is not working as expected.

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();

What is it wrong with this code?

Share Improve this question edited Dec 9, 2020 at 22:39 Federico Baù 7,8055 gold badges41 silver badges48 bronze badges asked Dec 1, 2016 at 9:03 SathishkumarSathishkumar 4393 gold badges8 silver badges21 bronze badges 1
  • 2 this is native js - why the tag for jQuery? – Pete Commented Dec 1, 2016 at 9:09
Add a ment  | 

1 Answer 1

Reset to default 5

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744958744a4603355.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信