Home>

I'm in trouble because I don't know how to solve it.
Excuse me, but please lend me your wisdom.

Prepare two HTML files as shown below
I'm loading the same css and js.

If i execute load of addEventListner in this state,
Only the instruction for box1 is executed, and box2 does not work properly.
* If the order is reversed, only box2 will be executed.

Also, when I check console.log, box2 seems to be null,
Uncaught TypeError: Cannot read property'classList' of null error is displayed.

I would appreciate it if you could teach me how to execute box2 as well.

html1

<bod
  
  
</body>


html2

<body>
  
  
</body>


css

# box1,
# box2 {
  width: 300px;
  height: 300px;
  background-color: blue;
  opacity: 0;
  transition: .5s;
}
# box2 {
  background-color: green;
}
# box1.show,
# box2.show {
  opacity: 1;
}


Javascript

const box1 = document.getElementById ('box1');
const box2 = document.getElementById ('box2');
window.addEventListener ('load', () =>{
  box1.classList.add ('show');
  box2.classList.add ('show');
})
  • Answer # 1

    Checking console.log, box2 seems to be null,

    exactly. Therefore, it is necessary to "skip the process if it does not exist".

    const box1 = document.getElementById ('box1');
    const box2 = document.getElementById ('box2');
    window.addEventListener ('load', () =>{
      if (box1) box1.classList.add ('show');
      if (box2) box2.classList.add ('show');
    })