我是一个完全的初学者,所以请帮助我理解为什么document.querySelectorAll不在这里工作?
<p id="demo">This is a paragraph.</p>
<h1 id="1demo"> Hello </h1>
<button type="button" onclick="myFunction()">Set font size</button>
<script>
function myFunction() {
document.querySelectorAll("#demo, #1demo").style.fontSize = "x-large";
}
</script>
我尝试了'getElementsByClassName‘以及class=的“演示”,只有当我指定“演示”或“演示”1时,它才起作用,但当只给出“演示”时,两者都不起作用。
发布于 2022-04-04 03:46:03
您需要迭代从querySelectorAll
返回的节点列表,并将样式单独应用于每个元素。同样,从数字开始的id选择器在querySelectorAll
中不能很好地工作,所以我将1demo
更改为demo2
。
function myFunction() {
const nodes = document.querySelectorAll("#demo, #demo2");
nodes.forEach(node => node.style.fontSize = "x-large");
}
<p id="demo">This is a paragraph.</p>
<h1 id="demo2"> Hello </h1>
<button type="button" onclick="myFunction()">Set font size</button>
发布于 2022-04-04 03:56:37
因为document.querySelectorAll返回一个节点列表。您必须遍历列表中的每个元素,才能访问每个元素的属性(如element.style.fontSize
)。
为了迭代,您可以有许多方法,如for...of回路、Array.forEach法或任何其他可以根据您的情况进行调整的迭代指令。
https://stackoverflow.com/questions/71728697
复制