js 节点操作出错
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Title</title> </head> <script type="text/javascript"> var img1=document.createElement("img"); img1.setAttribute("src","../img/1.jpg"); document.body.appendChild(img1); </script> <body> </body> </html>
Uncaught TypeError: Cannot read property 'appendChild' of null
img1怎么变为null ?
document.body为null,因为你的script位于body之上,在执行script的时候body还处于unload的状态。可在document加载完后执行该script,可改成这样:
window.onload = function () { var img1 = document.createElement("img"); img1.setAttribute("src", "1.jpg"); document.body.appendChild(img1); }