Skip to content
Advertisement

How to make JS querySelector check the DOM in real time

I’m trying to build a very basic chess board (with no embedded rules) as a learning challenge. Basically my board is made of 64 divs, where each div has a class .square. I have two functions: one for adding the .active class to the clicked square, and another function for moving the piece with the .active class to the new square. I’ve tried to put the two different eventListeners to call the different functions in an IF ELSE statement, but my condition doesn’t work because the querySelector doesn’t check in real time if there’s any div with the class .active at that given moment.

My code looks like this:

JavaScript

How do I make it check for the class in real time? Or is my approach completely wrong? Please be merciful, I’ve only been learning this stuff for a couple months, if I’m missing some basic knowledge please point it out so I can look it up.

Thanks!

Advertisement

Answer

In the event handler (a function that is called when a registered event is triggered) we use the Event Object property Event.target which always points to the tag that the user interacted with. Read the following articles for more details:

Events

Event Delegation

Details are commented in example

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement