window.addEventListener('DOMContentLoaded', () => {
const boxes = document.querySelector('#boxes');
let lastSelected = null;
// add the click eventlistener to the container #boxes
boxes.addEventListener('click', ({target}) => {
// If the element clicked on doesn't
// match a class of .box then exit.
if (!target.matches('.box')) return;
// if lastSelected has been set to an element
// then removed the .selected class
if (lastSelected) {
lastSelected.classList.remove('selected');
}
// add the .selected class to the currently clicked element
target.classList.add('selected');
// set lastSelected to this element, ready for the next click
lastSelected = target;
})
})
The if condition was their to check if lastSelected was null. I see you have changed it’s initial value from null to boxes. No biggy either way, I would say.
I agree it’s not a big thing (certainly not at this scale), but it’s one more line of execution in each evaluation of the function, that only needs to occur once (if null). Every time after the first, the if has to be evaluated unnecessarily shrug