Loading document with DOM

44 Views Asked by At

I am new to using Javascript to Web development. Recently, I've encountered this problem when trying to use DOMContentLoaded to my code below.

<!DOCTYPE html>
<html lang="en">

<head>
  <title>hello</title>
  <script>
    document.addEventListner('DOMContentLoaded', function(event) => {
      document.querySelector('#red').addEventListener('click', function() {
        let button = document.querySelector('button');
        button.style.backgroundColor = 'red';
        event.preventDefault();
      });
    });
  </script>
</head>

<body>
  <button id='red'> Red </button>
</body>

</html>

When I clicked the button, the color of the button did not change

I think that I've correctly implemented my code and added DOMContentLoaded event when placing the <script> in the head of my html code. However, this code does not work and so far I still not yet figure out where does the problem lies.

Could anyone help me with this matter and give me an explaination please? Thank you so much!

1

There are 1 best solutions below

0
hosien khedri On

place <script> in the body after the tags It's will work Good luck

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Document title</title>
</head>

<body>
  <button id='red'> Red </button>
  <script>
    document.addEventListner('DOMContentLoaded', function() => {
      document.querySelector('#red').addEventListener('click', function(event) {
        event.preventDefault();
        this.style.backgroundColor = 'red';
      });
    });
  </script>
</body>