3

I dont understand why when i click those elements with class click-to-open this function below does not work im trying to make something like a javascript accordion

document.getElementsByClassName('click-to-open').addEventListener('click', function(){
                document.getElementsByClassName('click-to-open').style.maxHeight = '40px';
                this.style.maxHeigh = '500px';
            });
Georgi Antonov
  • 1,581
  • 21
  • 40
  • Because getElementsByClassName return an array of elements, even if this is one, you need use event delegation for save resources and better performance, here and [article](https://davidwalsh.name/event-delegate) – dexhering Feb 04 '16 at 01:23

1 Answers1

1

Try this one :

var clickToOpen=document.getElementsByClassName('click-to-open');

for(var i=0;i<clickToOpen.length;i++){
     clickToOpen[i].addEventListener('click', function(){
                        this.style.maxHeight = '500px';
                    });
}

The method getElementsByClassName() always returns a set of class array, if you want to target all the DOM elements you need to iterate through all of them, if you were using Jquery there is a much more elegant way to do it.

This is a demo: https://jsfiddle.net/2tx2s3rz/2/ showing the code

Yehia Awad
  • 2,898
  • 1
  • 20
  • 31