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!
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!
- 3 If the code that you've written is in event handler, then you can directly use event.target.classList – Gangadhar Jannu Commented May 17, 2016 at 13:22
-
1
The place you want to get the
classList
is outside of the event handler, so no event has been triggered at that point. All you have is an array of elements inchangeAddress
. – Rhumborl Commented May 17, 2016 at 13:23 -
1
@AleshaOleg: So, what do you see from your
console.log
? Since it's inside the event, you should be able to dothis.classList
. – gen_Eric Commented May 17, 2016 at 13:27 -
1
@GangadharJannu thanks!
event.target.classList
work! Could you please answer this question? I will mark it as answer – AleshaOleg Commented May 17, 2016 at 13:29 -
1
@RocketHazmat it's
undefined
, butevent.target.className
works! – AleshaOleg Commented May 17, 2016 at 13:32
1 Answer
Reset to default 3In 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.
Using classList:
event.target.classList
will directly returns list of class names in an Array.Using className:
event.target.className
will return string representation of class names with space as seperator. So you can useevent.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