-1

I have a simple JS event:

var changeAddress = document.getElementsByClassName('modal-open');

if (changeAddress.length) {
    var a = 0;
    while (a < changeAddress.length) {
        changeAddress[a].addEventListener('click', function () {
            console.log(this); // Here i want to get classList
            document.querySelector('.modal').removeAttribute('hidden');
        });
        a++;
    }
}

How can I get classList from this?

It's not necessary get it from this or throw classList. I just want to get all class names of element on which event is triggered. Thanks!

AleshaOleg
  • 2,171
  • 1
  • 15
  • 29

1 Answers1

3

In the event handler callback you can get event as a parameter. With 'event' param we can get list of classes using either className or classList.

  1. Using classList: event.target.classList will directly returns list of class names in an Array.

  2. Using className: event.target.className will return string representation of class names with space as seperator. So you can use event.target.className.split("/\s") which will return array of class names.


We can use className or classList. className is supported by older browsers but modification (add, toggle, remove...) of classes is a tedious task, so classList is introduced and is easy to use.

However the classList property is not widely supported yet

Please refer Code with classList does not work in IE? for cross browser support

Community
  • 1
  • 1
Gangadhar Jannu
  • 4,136
  • 6
  • 29
  • 49