При клике ошибка Cannot read property 'style' of undefined

let x = document.querySelectorAll(".square")

for(i=0;i<x.length;i++){
    x[i].onclick = function(){
        x[i].style.backgroundColor = "blue"
    }
}
.square{
    width: 100px;
    height: 100px;
    background-color: red;
  margin:10px;
}
        <div class = "square"></div>
        <div class = "square"></div>
        <div class = "square"></div>


Ответы (1 шт):

Автор решения: Aziz Umarov

а так?

let x = document.querySelectorAll(".square")

for(let i=0;i<x.length;i++){
    x[i].onclick = function(){
        x[i].style.backgroundColor = "blue"
    }
}
.square{
    width: 100px;
    height: 100px;
    background-color: red;
  margin:10px;
}
<div class = "square"></div>
        <div class = "square"></div>
        <div class = "square"></div>

против

let x = document.querySelectorAll(".square")

for(var i=0;i<x.length;i++){
    x[i].onclick = function(){
        x[i].style.backgroundColor = "blue"
    }
}
.square{
    width: 100px;
    height: 100px;
    background-color: red;
  margin:10px;
}
<div class = "square"></div>
        <div class = "square"></div>
        <div class = "square"></div>

и ещё пример

let x = document.querySelectorAll(".square")

for(let i=0;i<x.length;i++){
    x[i].onclick = function(){
        x[i].style.backgroundColor = "blue"
    }
}

console.log(window.i)
.square{
    width: 100px;
    height: 100px;
    background-color: red;
  margin:10px;
}
<div class = "square"></div>
        <div class = "square"></div>
        <div class = "square"></div>

против

let x = document.querySelectorAll(".square")

for(i=0;i<x.length;i++){
    x[i].onclick = function(){
        x[i].style.backgroundColor = "blue"
    }
}

console.log(window.i)
.square{
    width: 100px;
    height: 100px;
    background-color: red;
  margin:10px;
}
<div class = "square"></div>
        <div class = "square"></div>
        <div class = "square"></div>

→ Ссылка