Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener to many elements selecting them with class [duplicate]

Tags:

javascript

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';
            });
like image 349
Georgi Antonov Avatar asked Nov 26 '25 04:11

Georgi Antonov


1 Answers

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

like image 132
Yehia Awad Avatar answered Nov 28 '25 23:11

Yehia Awad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!