为什么 getElementsByClassName 像这样工作?

时间:2021-06-15 07:41:46

标签: javascript html

首先,我真的很擅长javascript,我只是想为后天的考试做准备。为什么这个代码片段:

var colection=document.getElementsByClassName("old");
for(var i=0; i<colection.length;i++)
colection[i].className="new";

不工作?

另外,为什么会这样:

var colection=document.querySelectorAll(".old");
for(var i=0; i<colection.length;i++)
colection[i].className="nou";

或者这个:

var vector=[];
var colectie=document.getElementsByClassName("vechi");
for(var i=0;i<colectie.length;i++)
vector[i]=colectie[i];
for(var i=0;i<vector.length;i++)
vector[i].className="nou";

工作好吗?我们的老师只是告诉我们第一个不正确,但没有告诉我们确切的原因。

另外,如果第一个不起作用,为什么会这样:

<script>
window.onload=function()
{
var
list=document.getElementsByTagName("p");
alert("There are"+list.length+" paragraphs");
for(var p of list)
{p.style.color="red";}
}
</script>
</head>
<body>
<h1>Colectie</h1>
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>
<div>This is a div</div>
</body>

工作?

我真的想不通它们之间的区别...谢谢

1 个答案:

答案 0 :(得分:0)

getElementsByClassName 返回一个 live HTMLCollection 意味着它会自动更新自己。因此,通过更改元素 className,它会从列表中删除,减少长度使其跳过元素。

var colection=document.getElementsByClassName("old");
for(var i=0; i<colection.length;i++)
colection[i].className="new";

querySelectorAll 更像是执行时刻的快照。它不会自行更新。这意味着长度不会受到影响,它可以更改每个元素的 className。

var colection=document.querySelectorAll(".old");
for(var i=0; i<colection.length;i++)
colection[i].className="nou";

此示例将您的 live HTMLCollection 转换为一个数组。消除了长度变化的问题,因此跳过了元素。它们仍然会从 colectie 中删除,但由于您在 vector 上循环,它不会影响输出。

var vector=[];
var colectie=document.getElementsByClassName("vechi");
for(var i=0;i<colectie.length;i++)
vector[i]=colectie[i];
for(var i=0;i<vector.length;i++)
vector[i].className="nou";

尽管 getElementsByTagName 也返回一个 live HTMLCollection。在此循环中,您不会更改标签,因此集合的长度也不会更改,从而为您提供预期的输出。

var list=document.getElementsByTagName("p");
alert("There are"+list.length+" paragraphs");
for(var p of list) {
  p.style.color="red";
}
相关问题