为什么getElementById工作但不是getElementByClassName?

时间:2018-02-07 19:25:21

标签: javascript html

我最近开始学习JS,由于某种原因,我无法让 getElementByClassName 为我工作。这是我的代码。



//variable to store the ID h1
var id = document.getElementById("first");
//variable to store the class h1
var cs = document.getElementsByClassName("second");

//coloring the id 'first'
id.style.color = "red";

cs.style.color = "blue";

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test Site</title>
  </head>
  <body>
    <h1 id="first">This is an ID</h1>
    <h1 class="second">This is a class</h2>

    <script src="index.js"></script>
  </body>
</html>
&#13;
&#13;
&#13;

带有ID的元素正在改变颜色但是具有类的元素不是。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

getElementById 会返回一个单个元素,因为您在DOM中不应该有多个具有相同ID的元素。

getElementsByClassName 会返回 HTMLCollection ,因为许多元素可以共享相同的类名。

试试这个:

//variable to store the ID h1
var id = document.getElementById("first");
//variable to store the class h1
var cs = document.getElementsByClassName("second");

//coloring the id 'first'
id.style.color = "red";

cs[0].style.color = "blue";

在现实生活中,您可能希望循环遍历数组。

相关问题