-3

I have a rather odd issue that I can't seem to solve. I have written a code and I want to use it when a certain element has this specific class name, so I have done this:

function slide() {
    var box = document.getElementsByClassName('box'); 
    if(box.style.maxHeight !== "100px") {
        box.style.maxHeight = "100px";
        box.style.opacity = "1";
    } else {
        box.style.maxHeight = "0";
        box.style.opacity = "0";
    }
    return false;
}       

And the HTML:

<h1 onclick="slide();"> Text </h1>

<div class="box">
    <p>
         Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est.
    </p>
</div>

And the CSS:

.box {
    max-height: 0;
  }

I think I am missing something here, but I don't know what. The funny thing is: when I would use getElementById, it works! But I want to use classnames instead and that is not working.

The error I am getting is:

Uncaught TypeError: Cannot read property 'maxHeight' of undefined

halfer
  • 19,824
  • 17
  • 99
  • 186
Siyah
  • 2,852
  • 5
  • 37
  • 63

3 Answers3

2

Get Elements By ClassName returns a HTML Collection. You need to assign it on each elem:

var boxes = document.getElementsByClassName('box'); 
for(box of boxes){
 //work with elem
 if(box.style.maxHeight !== "100px") {
   box.style.maxHeight = "100px";      
   box.style.opacity = "1";
 } else { 
   box.style.maxHeight = "0";     
   box.style.opacity = "0";
}
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0
   var box = document.getElementsByClassName('box')[0];
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30
  • Please don't forget to explain / comment your code, and provide relevant documentation [from review] – Blag Jan 08 '17 at 15:20
-1

the getElementsByClassName return an array. Its items have the style property, not the array itself.

ValLeNain
  • 2,232
  • 1
  • 18
  • 37