1

i am trying to get the style of an element from html and trying to print on console. I cant see style option while typing the style property in visual code. its keep showing the error Uncaught TypeError: Cannot read properties of null (reading 'style') in javascript var element; element = document.querySelector("#header").style.backgroudColor; console.log(element);

<!DOCTYPE html>
<html>

  <head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='all.css'>
    <script src="javascript_code.js"></script>
  </head>

  <body>
    <div id="header" class="heading" style="background-color: red;">
      <h1>this is header</h1>
      <h1>this is header2</h1>
    </div>
    <script src="javascript_code.js"></script>
  </body>

  </html>
shine
  • 13
  • 3

3 Answers3

0

you have included javascript file two time first in the header and second at the last inside body tag. first remove one of them and there is a spelling mistake in backgroundColor as you can see here element = document.querySelector("#header").style.backgroundColor = 'green';

  • but the error still there. and i am jest getting the value from html document. – shine Mar 17 '22 at 06:29
  • the reason is in the `element` variable you have assign value only. If you want to assign an element inside the variable the code will be `element = document.querySelector("#header");` than only you can get actual element inside your variable. – haither azeez Mar 17 '22 at 06:46
  • After assign the element inside the variable you can add style. first `element = document.querySelector("#header");` than second `element.style.backgroundColor = 'green';` – haither azeez Mar 17 '22 at 06:48
  • var element; element = document.querySelector("#header"); var e2=element.style.backgroudColor; console.log(e2); – shine Mar 17 '22 at 08:45
  • still getting undefined. – shine Mar 17 '22 at 08:46
  • look at this video at 2:00 minutes. it works for him but not for me https://www.youtube.com/watch?v=JeuPPUjY4kQ – shine Mar 17 '22 at 08:52
0

you can use document.getElementById('header').style.backgroudColor like this.

0

i restarted the computer and all my snippets started working. the style property is now working.

shine
  • 13
  • 3