@Savextar

Применение стилей к элементу массива js. Почему возникает ниже описанная ошибка?

<body>
    <div class="container">
        
    </div>
    <script src="app.js"></script>
</body>

body{
    margin: 0;
    background-color: #111;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}

.container{
    max-width: 400px;
    display: flex;
    flex-wrap: wrap;
}

.square{
    height: 30px;
    width: 30px;
    background-color: #1d1d1d;
    box-shadow: 0 0 2px #000;
    margin: 2px;
    transition: 2s ease;
}

.square:hover{
    transition-duration: 0s;
}

const container = document.querySelector('.container')
const SQUARES = 121

for(let i = 0; i < SQUARES; i++){
    
    let square = document.createElement('div');
    square.classList.add('square');
    const squares = document.querySelectorAll('.square');

    square.addEventListener('click', function (element) {

        var parent = container;
        var index = Array.prototype.indexOf.call(parent.children, element.target);
        squares[index].style.background = '#fff';
    });

    

    container.appendChild(square)
}

Итак, squares[index].style.background = '#fff';, может ли кто-нибудь объяснить, почему нельзя применить стили к элементу массива, когда в качестве идентификатора стоит переменная?
Варианты:
squares[index-1] чтобы стилизовать соседний элемент
squares[12] чтобы стилизовать определенный объект
element.target.style.background = '#fff' или просто нажатый элемент работают

Тогда в чем проблема squares[index].style.background = '#fff';?
  • Вопрос задан
  • 80 просмотров
Решения вопроса 1
AlekSays
@AlekSays
FrontEnd developer
square.addEventListener('click', function () {
        this.style.background = '#fff';
    });
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы