1

I've started using atom to code my HTML, CSS and JS files, but have ran into some issue getting JS to work with the HTML document. I have the following code in place with the corresponding file names:

Code:

    var h1 = document.querySelector('h1');
    
    h1.onclick = function(){
      this.classList.add('highlight');
    }
CSS: 

    .highlight {
      color: white;
      background-color: blue;
    }
    
    h1 {
      font-style: italic;
    }
    <html>
     <head>       
       <title>Applying Multiple Styles</title>
     </head>
     <body>
       <h1>Highlight this element on a click</h1>
     </body>
    </html>

When opening up the file via chrome I see: Chrome view of the resulting code

Showing the title to be italic, meaning the CSS has worked, but upon clicking the text, it does not change colour like the JS says it should so the JS doesn't work but the CSS does? Any thoughts?

Tim
  • 4,170
  • 4
  • 32
  • 50
  • Please will you edit your question to include your code within the question itself (rather than an external image). – Tim Jul 02 '20 at 11:32
  • Okay, I've just done it. – Christopher Hallett Jul 02 '20 at 11:42
  • Check the browser's devtools, does it have any error? It could be that the script.js has not been found... – Alex Michailidis Jul 02 '20 at 11:44
  • Probably https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – str Jul 02 '20 at 11:45
  • Well, I just saw that your script is at the beginning of the element. That means that the time it is being executed the h1 element is not yet rendered. Simply move the script.js at the end of the element. – Alex Michailidis Jul 02 '20 at 11:45

2 Answers2

1

You're loading your script inside the <head>, therefore your script is evaluated before the body is rendered and your h1 doesn't exist at time of execution. For your script to be evaluated after the body has rendered, you could put your script tag at the end of the body:

<html>
 <head>
   <link href="styles.css" rel="stylesheet" type="text/css">
   <title>Applying Multiple Styles</title>
 </head>
 <body>
   <h1>Highlight this element on a click</h1>
   
   <script src="script.js"></script>
 </body>
</html>
cyr_x
  • 12,554
  • 2
  • 26
  • 42
1

When you load your script the DOM is not loaded So your doen't exists !

you need to put

<script src="script.js" defer></script>

or put the script call at the end of the body

AlexB
  • 61
  • 1
  • 8