DOM JS TypeError

Hi everyone!

I tried to make a dynamic grid of 12 cases (4 columns and 3 rows).
I need to generate 12 divs. Each one is a grid child and has a “hit” class and a data-id between 0 and 11.

But my console displays : Uncaught TypeError: document.querySelector(…).createElement is not a function at line 11.

let newCase = document.querySelector('.grid').createElement('div');

from :

let caseTaille = 84;
let gridRows = 3;
let gridColumns = 4;
let gridWidth = caseTaille * gridColumns;
let gridHeight = caseTaille * gridRows;
let total = gridRows * gridColumns;

for (i = 0; i < total; i++) {
    // Create child boxes in grid div
    let newCase = document.querySelector('.grid').createElement('div');
    let dataId = newCase.getAttribute('data-id');

    // Increment data-id
    dataId ++;

    // Positioning of the boxes in the grid = dataId / gridWidth; = dataId % gridWidth;

Index.html :

<!DOCTYPE html>

<html lang="en">


  <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>Exercice modulo</title>



  <div class="grid"></div>

  <script src="index.js"></script>



Does anyone know why? I checked the MDN documentation and I think I used the methods correctly.

Thank you and have a nice day!

According to the docs:

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors.

seems you get a group of selectors (which I assume is an array)? Difficult to say without seeing the full code, maybe make a codepen or a gist?

You could log the result of document.querySelector('.grid') to see what you get

also try to minimize DOM interaction, try to retrieve the element once, then try to insert all the elements at once. DOM manipulation is expensive

1 Like

Hi stetim!

Thanks for your feedback! I did a console.log and it selected the right div.
I edited my post to share my index.html. I hope this will be clearer! :grinning:

Been a while since I done Javascript like this, seems you need to use document.createElement like done in the docs:

Document.createElement() - Web APIs | MDN

and then use appendChild (docs).

an HTML is called a node in Javascript, these docs might help, all the node methods are listed here.