-1

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>
Soma Juice
  • 369
  • 1
  • 11

2 Answers2

2

You haven't initialized the variable i. Also the query selector is not correct. Here's a working codesandbox example: https://codesandbox.io/s/naughty-frog-bje4jw

Manish Gharat
  • 400
  • 1
  • 10
1

This might help to isolate it inside div #bars

document.querySelector('#bars div:nth-child(${i})').innerHTML = "Hello World!";
Helio
  • 621
  • 1
  • 4
  • 24