Why does style return null?

Asked

Viewed 243 times

0

Uncaught TypeError: Cannot read property 'style' of null
    at window.onload (main.js:7)

Because the load object does not appear, it is null?

window.onload = function() {



  load = document.createElement('div');
  load.id = 'load';
  document.getElementById('load').style.height = Math.round(window.innerHeight);
  console.log(load)

}

1 answer

1


How are you creating the div via javascript, this command

document.getElementById('load');

It will only work after you add it to your HTML. Ex.:

let load = document.createElement('div');
load.innerHTML='MinhaDiv';
load.id='load';
document.body.appendChild(load);
document.getElementById('load').style.border='1px solid red';

Now note the following you are creating the div and playing it for variable load.
On the spot where you’re doing the .getElementById(), you could just use the variable load which is already available there at that moment.

window.onload = function() {
  let load = document.createElement('div');
  load.id = 'load';
  //document.getElementById('load').style.height = Math.round(window.innerHeight);
  load.style.height = Math.round(window.innerHeight);
  console.log(load);
  
  // escrevendo algo nela
  load.innerHTML = 'Ola';
  // adicionando ao body
  document.body.appendChild( load );
}

References

appendchild, createelement

Browser other questions tagged

You are not signed in. Login or sign up in order to post.