简体   繁体   中英

Javascript giving error only on load

The following is the javascript I wrote in my js file:

var ele = document.getElementsByTagName('body');
var p = document.getElementById('hello');
ele[0].innerHTML= p.innerHTML;

But it gives error that p is null. But when I run the same commands in console, they work perfectly. Can someone please help me figure this out.

As users suggested, it's about if the DOM is rendered or not when you run JS. You have 2 options.

  1. When you link the script in the <head> , make sure to wrap it in onload , see example below
  2. When you link the script in the <body> , you don't need to wrap it in onload

     // example window.onload = function(){ // or better use window.addEventListener // do some stuff or paste your code here } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM