Inserting value in nth child with forEach loop

Viewed 43

im trying to to update a whole bunch of nth children with a loop, but i run into this problem in the web console:

Uncaught TypeError: document.querySelector(...) is null.

When i look at the web page there is one instance of hello world.

following the example of Use variables in document.querySelector What i am doing should be working so i cant figure out what is wrong?

function randomNumberArr() {
  let arr = Array.from({ length: 5 }, () => Math.floor(Math.random() * 31));
  return arr;
}

function displayData(arr) {
  let i = 0;
  arr.forEach(function () {
    i++;

    //works:
    //document.querySelector(`div:nth-child(2)`).innerHTML = "Hello World!";
    //dont work:
    document.querySelector(`div:nth-child(${i})`).innerHTML = "Hello World!";
  });
}
let arrNumbers = randomNumberArr();

displayData(arrNumbers);

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>

    <div id="bars">
        <div id="bar"></div>
        <div id="bar"></div>
        <div id="bar"></div>
        <div id="bar"></div>
        <div id="bar"></div>
    </div>
<script src="test.js"></script>
</body>
</html>
2 Answers

This might help to isolate it inside div #bars

document.querySelector('#bars div:nth-child(${i})').innerHTML = "Hello World!";
Related