简体   繁体   中英

how to fix it: “Uncaught TypeError: Cannot read property 'addEventListener' of null”…?

Im learning html/css/js from a video tutorial. Im learning how to write js code ans i cant help to solve a problem. I hope you give me the solution guys. The problem is about add.EventListener. When i run the code in chrome, in console it shows:"app.js:11 Uncaught TypeError: Cannot read property 'addEventListener' of null" I hope solve this problem with your help. Thank you!

const computerScore = 0;
const userScore_span = document.getElementById("user-score");
const computerScore_span = document.getElementById("computer-score");
const scoreBoard_div = document.querySelector(".score-board");
const result_div = document.querySelector(".result");
const p_div = document.getElementById("p");
const r_div = document.getElementById("r");
const s_div = document.getElementById("s");

p_div.addEventListener('click', function() {
    console.log("hey you clicked on p");
})`

document.getElementById('p') will return null when there is no element on the page with that id. I'd recommend looking through your HTML and making sure you actually have an element with that id.

You can console.log(p_div) after you create that constant to see the value of that element before you try to addEventListener

You can check if p_div exist.

if(p_div) {
  p_div.addEventListener('click', function() {
    console.log("Hey you clicked on p");
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM