我正在用 javascript 创建一堆 div,并且在某个时间我希望删除所有 div。
我的代码是这样的:
function CreateDiv(width, height, row, col){
var thisTile = document.createElement("div");
thisTile.style.position = "absolute";
thisTile.style.width = width + "px";
thisTile.style.height = height + "px";
thisTile.style.top = row*TileH + topMargin + "px";
thisTile.style.left = col*TileW + leftMargin +"px";
thisTile.style.backgroundImage = "url(" + imagePath + ")";
thisTile.style.backgroundSize = imageWidth + "px " + imageHeight +"px";
thisTile.style.backgroundRepeat = "noRepeat";
thisTile.style.backgroundPosition = "-" + col*TileW + "px -" + row*TileH + "px";
thisTile.onclick = TileClicked;
thisTile.name = "tiles";
document.body.appendChild(thisTile);
return thisTile;
}
...
var tmp = document.getElementsByName("tiles");
alert("tmp length: " + tmp.length);
for (var i = 0; i < tmp.length; i++)
document.body.removeChild(tmp[i]);
但每次 tmp 都是一个空数组,所以我实际上无法删除我想要的 div,
我试图改变
tile.name = "tiles"
到
tile.nodeName = "tiles"
或者
tile.className = "tiles"
但是它们都不起作用,我只是想知道元素的哪个名称属性或属性究竟是getElementsByName中的那个?