getElementsByClassName doesn't work, but getElementById does?

Jack Elwell picture Jack Elwell · Aug 27, 2016 · Viewed 9k times · Source

I've written a script, it's goal is to stop displaying images one and two, while allowing image 3 to remain displayed and move into their place. It works fine when I use div Id's instead of div Classes, but I would prefer to use div classes so I can group the elements like this:

 function myFunction() {
     var y = document.getElementsByClassName("firstimage secondimage");
     if (y.style.display === 'none') {
           y.style.display = 'block';
     } else {
           y.style.display = 'none';
     }
 }

rather than this (in order to save space should I choose to include more elements):

 function myFunction() {
     var x = document.getElementById("firstimage");
     if (x.style.display === 'none') {
          x.style.display = 'block';
     } else {
          x.style.display = 'none';
     }

     var y = document.getElementById("secondimage");
     if (y.style.display === 'none') {
          y.style.display = 'block';
     } else {
          y.style.display = 'none';
     }
}

I thought that just changing the div id's to div classes, and the #imagenumber's to .imagenumber's (in addition to the change in the javascript I described above) would work but the script stops working when I do. I need the script to function in the same way that the code I am pasting below does, but with div classes instead of div Id's. Please tell me where I am going wrong.

CSS:

#firstimage {
    width: 100px;
    height: 100px;
    padding: 0px 0;
    text-align: center;
    background-color: green;
    margin-top:20px;
    color: white;
}

#secondimage {
    width: 100px;
    height: 100px;
    padding: 0px 0;
    text-align: center;
    background-color: blue;
    margin-top:20px;
    color: white;
}

#thirdimage {
    width: 100px;
    height: 100px;
    padding: 0px 0;
    text-align: center;
    background-color: red;
    margin-top:20px;
    color: white;
}

HTML:

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

<div id="firstimage">
    DIV element.
</div>

<div id="secondimage">
    A second DIV element.
</div>

<div id="thirdimage">
    A third DIV element.
</div>

Javascript:

function myFunction() {
     var x = document.getElementById("firstimage");
     if (x.style.display === 'none') {
          x.style.display = 'block';
     } else {
          x.style.display = 'none';
     }

     var y = document.getElementById("secondimage");
     if (y.style.display === 'none') {
          y.style.display = 'block';
     } else {
          y.style.display = 'none';
     }
}

Answer

Sterling picture Sterling · Aug 27, 2016

document.getElementsByClassName returns an array of elements, so you would need to iterate through that array and operate on each element within that loop.