skip to Main Content

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


  1. Keep your dev tools open so you can see when errors are thrown – it says that p is not defined. You defined p in your for loop, but you are referencing it in your listener func, which does not have p in scope. You would be better off doing something like this:

    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'
    
      // add an event listener for each p
      p.addEventListener('click', function (event) {
        console.log("Hello World");
        p.style.backgroundColor = "yellow";
      }, false);
    }
    <div id="divmain">
      <div id="parent"></div>
    </div>
    Login or Signup to reply.
  2. 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.

      let htmlString = "";
      let height = 4;
      let row = 4;
      let parent = document.querySelector('#parent');
      let p; // Declare p outside the loop
    
      for (let i = 1; i <= 9; i++) {
          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);
    
    Login or Signup to reply.
  3. The p variable is not defined. Either you need to set a listener in the loop as @twharmon suggested or use event.target instead of p:

    event.target.style.backgroundColor = "yellow";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search