Why this simple thing not working - getElementsByClassName

OK I am selecting a li from its ul. This code works when used with getElementById.

<html>
<head>
 
<script>
function myFunction() {
    document.getElementById("list").children[1].style.backgroundColor = "lightblue";
}
</script>
 
</head>
<body>
 
<ul id="list">
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
 
<button onclick="myFunction()">Try it</button>
 
</body>
</html>

But stops working when used with getElementsByClassName

<html>
<head>

<script>
function myFunction() {
    document.getElementsByClassName("list").children[1].style.backgroundColor = "lightblue";
}
</script>

</head>
<body>

<ul class="list">
<li>A</li>
<li>B</li>
<li>C</li>
</ul>

<button onclick="myFunction()">Try it</button>

</body>
</html>

Please help. Thank you.

Are you getting any messages in the console for it? A couple of Codepens of the two versions might be useful too.

This is what the console shows:

As you can see by the name getElementsByClassName, Elements is plural, whereas getElementById is singular.

Even if there’s only one instance of the class name, you still have to tell JS what number it is. E.g.

document.getElementsByClassName("list")[0].children[1].style.backgroundColor = "lightblue";
2 Likes

Thank you Chris.

Thank you Ralph… Now I understand…

Topic closed.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.