I have this code in jQuery:
var clickClasses = '.btn1.btnh, .btn-consent-accepted, .btn-consent-save-accepted, .btn-consent-save-reject, .btn-consent-save-settings';
jQuery(document).on('click', clickClasses, function (e) {
//do something
});
It works perfectly in jQuery, but I would like to have this in plain JavaScript.
Any help is greatly appreciated!
PS: some classes are loaded dynamically (ajax), hence my jQuery function
jQuery(document).on(‘click’….).
2
Answers
You can convert your string to array of classes, loop through them, find single element and add event listener on them like below
Add the
click
event listener to thedocument
and check if any of the elements have been clicked with theElement.closest()
. That method runs up the DOM tree from the element you call it on and evaluates the selector on any element it passes.If no element in the string is found, then it returns
null
.