Home > Enterprise >  Why I cant iterate the the variable **element** in my forEach loop. *It says Uncaught ReferenceError
Why I cant iterate the the variable **element** in my forEach loop. *It says Uncaught ReferenceError

Time:11-13

Why I cant iterate the the variable element in my forEach loop. It says Uncaught ReferenceError: element is not defined

    const board = document.getElementById("board");
    const array = [1, 2, 3, 4, 5, 6, 7, 8];
    createELementOverArray();
    function createELementOverArray() {
      array.forEach((value) => {
        const element = document.createElement("div");
        board.appendChild(element);
        console.log(element);
      });
    }

I EXPECTED TO BE LIKE THIS

 <div id="board">
      <div ></div>
      <div ></div>
      <div ></div>
      <div ></div>
      <div ></div>
      <div ></div>
      <div ></div>
</div>
Why I cant iterate the the variable **element** in my forEach loop. *It says Uncaught ReferenceError: element is not defined*

CodePudding user response:

seems the error coming from this line

      board.appendChild(element);

In fact you are defining 'board' but is board in your document? Check the snippet, div board is in the HTML. I've also added the line to add the class in javascript

const board = document.getElementById("board");
const array = [1, 2, 3, 4, 5, 6, 7, 8];
createELementOverArray();

function createELementOverArray() {
  array.forEach((value) => {
    const element = document.createElement("div");
    element.classList.add('element');
    board.appendChild(element);
    console.log(element);
  });
}
<div id="board">
</div>

  • Related