Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Event is not running

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)";       
    });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading