-1

I created 64 class in numbers (1,2,3,4...) and it seems that there are a lot of case specific things to do so I can use them normally like this

document.querySelector(".\\" + number)

For some reason when I try to create an img inside the div it says that it dosen't exist.

Here's the code related to the error:

HTML:

<div id="board">
<div style="width: 61.2219px; height: 61.2219px;" class="1"></div>
<div style="width: 61.2219px; height: 61.2219px; background-color: white;" class="2"></div>
<div style="width: 61.2219px; height: 61.2219px;" class="3"></div>
<div style="width: 61.2219px; height: 61.2219px; background-color: white;" class="4"></div>
<div style="width: 61.2219px; height: 61.2219px;" class="5"></div>
<div style="width: 61.2219px; height: 61.2219px; background-color: white;" class="6"></div>
...
<script src="main.js"></script>

JS:

while (x != 8)
{ **// Generates DIV**
  if (last == 0)
  {
    last = 1;
  }
  else
  {
    last = 0;
  }

  while (y != 8)
  {
    var div = document.createElement("div");
    div.style.width = width;
      div.style.height = width;
    if (last == 0)
    {
      div.style.backgroundColor = "white";
      last = 1;
    } else 
    {
      last = 0;
    }
    div.classList.add(((x*8)+y)+1)
    board.appendChild(div);
    y++;
  }
  y=0
  x++;
}
...
while(x != startpos_len)
{
  console.log(x);
  let name = ".\\" + (x+1)
  var imgPiece = document.createElement("img");
  switch(startpos[x])
  {
    case "BR":
      img.src = "."
    default:
      // alert("Startpos contain errors")
  }
  **document.querySelector("div" + name).appendChild(imgPiece);**
  x++;
}

PS: This is a chess game

I tried reading documentation on Mozilla, w3school and similar error on stack overflow, but nothing was working.

Also defer in didn't change anything

Changing to ID's or adding letters in the class didn't work

1 Answers1

1

Your selector syntax is incorrect.

Your options are...

Preferably use id attributes that are actually selectable. This makes sense given you seem to want unique elements (chessboard positions)

<div style="width: 61.2219px; height: 61.2219px;" id="pos-1"></div>
document.getElementById(`pos-${x+1}`)?.appendChild(imgPiece);

OR

Not recommended... keep the (bad) numeric classes and use an attribute selector. Note the quotes around the value are required

document.querySelector(`div[class='${x+1}']`)?.appendChild(imgPiece);

Note that this only works with class attributes that are single-token. If there are other classes involved, eg class="foo bar baz 1", it gets more complex

document.querySelector(
  `div[class='1'], div[class^='1 '], div[class$=' 1'], div[class*=' 1 ']`
);
Phil
  • 157,677
  • 23
  • 242
  • 245