skip to Main Content

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


  1. You can convert your string to array of classes, loop through them, find single element and add event listener on them like below

    var clickClasses = '.btn1.btnh, .btn-consent-accepted, .btn-consent-save-accepted, .btn-consent-save-reject, .btn-consent-save-settings';
    var classArray = clickClasses.split(", ");
    classArray.forEach(function(singleClass) {
      document.querySelector(singleClass).addEventListener('click', handleClick);
    });
    
    function handleClick(e) {
      console.log("Element clicked " + e.target.innerHTML);
    };
    
    Login or Signup to reply.
  2. Add the click event listener to the document and check if any of the elements have been clicked with the Element.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.

    const clickClasses = '.btn1.btnh, .btn-consent-accepted, .btn-consent-save-accepted, .btn-consent-save-reject, .btn-consent-save-settings';
    
    document.addEventListener('click', event => {
      const clickTarget = event.target.closest(clickClasses);
      
      if (clickTarget === null) {
        return;
      }
    
      // do something.
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search