gpt4 book ai didi

javascript - JS改变所有 'p'颜色

转载 作者:行者123 更新时间:2023-11-28 13:00:33 24 4
gpt4 key购买 nike

我想更改所有“p”元素的颜色,我尝试使用此代码执行此操作,但它不起作用。

document.getElementsByTagName('p').forEach(element => {
element.style.color = 'white'
});

有没有正确的方法(不使用JQuery)?

最佳答案

您可以使用普通 JavaScript ES2015 (ES6) 代码来完成此操作。

document.querySelectorAll('p').forEach(e => e.style.color = "white");

更新:

我忘了提及,这是在 DOM 中应用元素的白色,效率不高,因此您也可以通过其他方式执行此操作。

CSS:

.white {
color: #fff;
}

JavaScript:

// If you have just one class for the element
document.querySelectorAll('p').forEach(e => e.className = 'white');

// If you are appending the class of `white`
document.querySelectorAll('p').forEach(e => e.className += ' white');

关于javascript - JS改变所有 'p'颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51005059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com