[英]How do i use document.getElementById(“mydiv”) to edit multiple divs with the same ID
我有的是
<script>
function myFunction()
{
document.getElementById("post").style.backgroundColor="#ECF6A4";
}
</script>
<button onclick="myFunction()">Change Post Color</button>
在頁面中,有多個帶有id =“ post”的div,但是當我保存代碼並嘗試使用它時,它僅更改了帶有id =“ post”的頁面上第一個div的背景,而沒有其他任何背景。
我沒有運氣就嘗試了getElementsById,這就是我能想到的。
有任何簡單的解決方案嗎?
同一頁面上具有相同ID的多個div無效標記,重復ID無效。
因此請使用類pls,因此
getElementsByClassName()
遍歷他們
當您要引用多個元素時,應使用class而不是id。
document.getElementsByClassName('class').style.backgroundColor = "#ECF6A4"
因為我已經完成了演示
您寫道: trying getElementsByClassName() but nothing changes
,原因是getElementsByClassName()
返回了一個數組,您必須訪問此數組的每個元素,然后才能使用.style.backgroundColor="#ECF6A4";
function myFunction()
{
var listItems = document.getElementsByClassName("even");
for (var i = 0; i < listItems.length; i++)
{
listItems[i].style.backgroundColor="#ECF6A4"; // element i of array
}
}
和HTML
<ul>
<li class="odd">1</li>
<li class="even">2</li>
<li class="odd">3</li>
<li class="even">4</li>
<li class="odd">5</li>
<li class="even">6</li>
</ul>
<button onclick="myFunction()">Change Color for even</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.