[英]getElementsByTagName doesn't apply to every tag
I'm trying to change the color of every h1 in my page but it doesn't change to anything with this code: 我正在尝试更改页面中每个h1的颜色,但是此代码不会更改为任何颜色:
function toggleDark() { document.body.style.background = "#1e1e1e"; document.body.style.color = "#fff"; document.getElementsByTagName("h1").style.color = "#fff"; }
<body> <a href="#" onclick="toggleDark()">DM</a> <section> <div class="container"> <h1>WLJ</h1> </div> <div> <h1>BB</h1> </div> </section> </body>
However when I click I add an [0], it works but only with the first h1... 但是,当我单击[0]时,它只能在第一个h1上工作。
document.getElementsByTagName("h1")[0].style.color = "#fff";
I don't know what's wrong with my code, what I want is to get every h1 in white when clicking on the 我不知道我的代码有什么问题,我想要的是在单击
Thanks. 谢谢。
Document.getElementsByTagName()
returns HTMLCollection . Document.getElementsByTagName()
返回HTMLCollection 。 You have to loop through all the element to set the style individually: 您必须遍历所有元素才能分别设置样式:
function toggleDark() { document.body.style.background = "#1e1e1e"; document.body.style.color = "#fff"; [...document.getElementsByTagName("h1")].forEach(function(h){ h.style.color = "#fff"; }); }
<body> <a href="#" onclick="toggleDark()">DM</a> <section> <div class="container"> <h1>WLJ</h1> </div> <div> <h1>BB</h1> </div> </section> </body>
Here is my contribution. 这是我的贡献。
As Mamun stated, document.getElementsByTagName()
returns a HTMLCollection . 如Mamun所述,
document.getElementsByTagName()
返回HTMLCollection 。
You can iterate it and then set the colour to individual elements: 您可以对其进行迭代,然后将颜色设置为单个元素:
function toggleDark() { document.body.style.background = "#1e1e1e"; let headers = document.getElementsByTagName("h1"); for (let i = 0; i < headers.length; i++) { headers[i].style.color = "#fff"; } }
<a href="#" onclick="toggleDark()">DM</a> <section> <div class="container"> <h1>WLJ</h1> </div> <div> <h1>BB</h1> </div> </section>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.