簡単な例で問題を説明します。次のhtmlページがあります。それは簡単です。
TestDiv という名前の 1 つの CSS クラスと 2 つの JavaScript 関数があります。
- addDivは新しい div を作成し、 「新しい div を追加」ボタンをクリックしてページに追加します。
- setBlueは、クラスTestDivを持つ div の色を変更したい関数であり、方法がわかりません。
setBlue関数内で現在生成されている Div を変更するコードを書いていることがわかります。しかし、クラスを変更して、その後addDiv関数によって生成される新しい div に影響を与える方法がわかりません。
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.TestDiv {
color:red;
}
</style>
<script>
function addDiv() {
var newDiv = document.createElement("div")
newDiv.className = "TestDiv";
newDiv.innerHTML = "test";
document.getElementById("firstDiv").insertBefore(newDiv);
}
function setBlue() {
var currentDivList=document.getElementsByClassName("TestDiv");
for(var i=0;i<currentDivList.length;i++){
currentDivList[i].style.color = "blue";
}
// What i can write here to change the TestDiv css class
// And after that, new (div)s will generate by new color(changed css class)
}
</script>
</head>
<body>
<div id="firstDiv" class="TestDiv">
test
</div>
<input type="button" value="add new div" onclick="addDiv();"/>
<input type="button" value="change color to blue" onclick="setBlue();"/>
</body>
</html>