Home > Net >  Event is not running
Event is not running

Time:11-05

const face = document.querySelector('.face');
const con = document.querySelector('.con');

for (let i = 0; i < face.length; i  ){
con.addEventListener("click" , () => {
        face[i].style.transform = "translateZ(600px)";       
    });
}

I wanted to change a CSS property as you see in the code. But even though the con element is being clicked, no action is happening. The event I have written for con for the action click not running. Actually there are five face elements in that con element in HTML code.

CodePudding user response:

First of all, the first problem is that you want a single element selected with querySelector to contain more than one element. Which is impossible, instead you can select all available elements with querySelectorAll.

Then instead of looping through the index, you can fetch each children so you don't have to select them later.

Final Code:

const faces = document.querySelectorAll('.face');
const con = document.querySelector('.con');

for (const face of faces){
    con.addEventListener("click" , () => {
        face.style.transform = "translateZ(600px)";       
    });
}

CodePudding user response:

You did a querySelector, if you have five con, you have to do :

const con = document.querySelectorAll('.con') or const con = document.querySelectorAll('.face') if you want to select multiple face.

  • Related