[英]How to change font color of all elements of a class through javascript?
我有一個按鈕可以更改我的 Web 應用程序的背景圖像,我想在單擊該按鈕時更改字體的顏色。
我嘗試使元素成為自己的變量,但這也不起作用。
cafeButton.addEventListener('click', function(){
bg.style.backgroundImage = "url('img/cafe.jpeg')"; //change text colors
document.getElementsByClassName('topbutton').style.color = 'blue';
})
使用上述代碼時,出現以下錯誤:
未捕獲的類型錯誤:無法在 HTMLButtonElement 處設置未定義的屬性“顏色”。
這里是整個項目的codepen https://codepen.io/Games247/pen/XWJqebG
如何更改類名下所有元素的文本顏色?
document.getElementsByClassName
返回一個 DOM 節點列表。 因此,您需要遍歷它並將樣式單獨應用於所有元素。
cafeButton.addEventListener('click', function() {
bg.style.backgroundImage = "url('img/cafe.jpeg')"; //change text colors
var els = document.getElementsByClassName('topbutton');
for (var i = 0; i < els.length; i++) {
els[i].style.color = 'blue';
}
})
getElementsByClassName
為您提供DOMCollection
,它只是數組。 因此,您必須為數組中的每個元素設置樣式。 例如。
[...document.getElementsByClassName('topbutton')].forEach((ele)=>{ele.style.color = 'blue';});
你這樣做是錯誤的。 document.getElementsByClassName
為您提供特定類的節點列表。 所以你必須遍歷它。 所以,在你的代碼中使用這個:
var nodeList = document.getElementsByClassName('topbutton')
nodeList.forEach(node => {
node.style.color = 'blue'
})
或者你也可以使用document.querySelectorAll('.topbutton')
而不是document.getElementsByClassName('topbutton')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.