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
1 Answer
Reset to default 5a 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条)