[英]How to create div element on page load in JavaScript using createElement function?
I want to create a div element on page load event but my script is not working as expected.我想在页面加载事件上创建一个 div 元素,但我的脚本没有按预期工作。
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?这段代码有什么问题?
a few issues:几个问题:
first the tag name body
needs to be wrapped in quotes.首先标签名称
body
需要用引号括起来。 in your code you are passing an undeclared variable called body.在您的代码中,您正在传递一个名为 body 的未声明变量。
Secondly, its getElementsByTagName()
asthis function returns multiple elements in an array.其次,它的
getElementsByTagName()
函数返回数组中的多个元素。
Lastly, you need to target the first body element:最后,您需要定位第一个 body 元素:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.