これを克服するために2つのアイデアがあります。1 つ目は、要素を作成し、そのスタイルを変更して追加することです。
<script type="text/javascript">
for (var i = 0; i < 5; i++) {
var div = document.createElement("div");
div.style.width = "200px";
div.style.backgroundColor = "yellow";
document.appendChild(div);
}
</script>
もう 1 つのアイデアは、スタイルを変更するだけなので、DOM 要素への参照は必要なく、CSS でスタイルを適用できるということです。例えば:
<style type="text/css">
div.something {
width: 200px;
background-color: yellow;
}
</style>
<script type="text/javascript">
for (var i = 0; i < 5; i++) {
document.write("<div class='something'>text</div>");
// Or use the createElement/appendChild approach from above,
// where you'd need to set the div.className property as "something"
}
</script>