Home javascript Uncaught TypeError: Cannot read property 'style' of null

Uncaught TypeError: Cannot read property ‘style’ of null

Author

Date

Category

Hello, I got a problem – Uncaught TypeError: Cannot read property ‘style’ of null

function showSignin () {
  var container = document.querySelector ('. container');
  var form = document.createElement ('div');
  form.className = 'signin';
  form.innerHTML = '& lt; div id = "gray" & gt; & lt; / div & gt; & lt; div class = "window" & gt; & lt; img class = "close" src = "../ img / cancel-cross. svg "onclick =" closeSignin () "& gt; & lt; div class =" form "& gt; & lt; h2 style =" color: # E8BB49; "& gt; Authorization & lt; / h2 & gt; & lt; form method =" post "action = "includes / authorization.php" & gt; & lt; br / & gt; & lt; input type = "text" name = "username" required placeholder = "Username" class = "input__authorization" & gt; & lt; br / & gt; & lt; br / & gt; & lt; input type = "password" name = "password" required placeholder = "Password" class = "input__authorization" & gt; & lt; br / & gt; & lt; br / & gt; & lt; button type = "submit" name = "button" style = "background: # E8BB49; border: 1px solid # E8BB49; border-radius: 4px; color: # 403C3C; width: 300px; height: 40px; font-size: 24px;" & gt; Login & lt; / button & gt; & lt; / form & gt; & lt; / div & gt; & lt; / div & gt; ';
  var gray = document.getElementById ('gray');
  gray.style.backgroundColor = 'rgba (1, 1, 1, 0.75)';
  gray.style.position = 'fixed';
  gray.style.left = 0;
  gray.style.right = 0;
  gray.style.top = 0;
  gray.style.bottom = 0;
  gray.style.zIndex = -1;
  gray.style.display = 'none';
  container.insertBefore (form, container.children [0]);
  gray.style.display = 'block';
}

Answer 1

The

form is created dynamically … HTML elements are pushed inside it, but you request the element by id even before it is added to the page. You can request getElementById () only after the element is added to the document, for example, via appendChild ()

There are two options … either create gray dynamically and get it during creation, or first add the form where necessary (your line .insertBefore ), and only then request an id from there.

But in your case there is no need to get the element. Because you only use it to add styles … but they can be directly in the CSS and written right away:

& lt; style & gt; #gray {background-color: rgba (1, 1, 1, 0.75); etc. } & lt; / style & gt;

And if there is still an urgent need to add a lot of styles in JS, it is easier to write it like this:

element.style.cssText = "all styles in one line";

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions