I generated some divs with a loop and I can’t change their color (or any of their properties) via aJavaScript event listener (The console log works, so the event listener is working).
const main = document.getElementById('divmain');
let parent = document.querySelector('#parent');
for (let i = 1; i <= 9; i++) {
let p = document.createElement('div');
p.classList.add("pixel");
parent.appendChild(p);
p.textContent = 'Hello World!';
p.style.color = 'blue';
}
document.addEventListener('click', function (event) {
if (!event.target.matches('.pixel')) return;
console.log("Hello World");
p.style.backgroundColor = "yellow";
}, false);
The background should change to yellow but not
3
Answers
Keep your dev tools open so you can see when errors are thrown – it says that
p
is not defined. You definedp
in your for loop, but you are referencing it in your listener func, which does not havep
in scope. You would be better off doing something like this:The variable p is defined inside the loop, so it’s not accessible outside the loop. To fix this, you need to declare p outside the loop so that it can be referenced later in the event listener.
The
p
variable is not defined. Either you need to set a listener in the loop as @twharmon suggested or useevent.target
instead ofp
: