"document.querySelector(...) is null"即使它存在



我创建了64个数字类(1,2,3,4…),似乎有很多特定的事情要做,所以我可以像这样正常使用它们

document.querySelector(".\" + number)

由于某些原因,当我试图在div中创建一个img时,它说它不存在。

下面是与错误相关的代码: 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:这是一盘象棋

我试着阅读Mozilla, w3school和类似的堆栈溢出错误的文档,但没有任何工作。

Also defer in没有改变任何东西

更改ID或在类中添加字母不起作用

选择器语法不正确。

你的选项是…

最好使用实际可选择的id属性。这是有意义的,因为你似乎想要唯一的元素(棋盘位置)

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

不推荐…保留(坏的)数字类并使用属性选择器。注意值周围的引号是必需的

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

注意,这只适用于单令牌的类属性。如果涉及到其他类,例如class="foo bar baz 1",则会变得更复杂

document.querySelector(
`div[class='1'], div[class^='1 '], div[class$=' 1'], div[class*=' 1 ']`
);

最新更新