0

In my develop process, I meet a scenario: I only want to load a JavaScript file when a page has an element whose class is test, so what can I do? How to know a page whether has this element?

2
  • Instead of testing for pages with a class of test, why not attach the js file in the same place as the logic where the test class is being added? Commented Jan 25, 2021 at 2:29
  • 1
    Because the test calss is added in ckeditor, and we have many sites has the same class.
    – MyMercury
    Commented Jan 25, 2021 at 3:48

1 Answer 1

0

Well one way would be to just add the script always and check for the existence of test class there.

(function ($, Drupal) {
    Drupal.behaviors.tester = {

        attach: function (context) {
           if (context.querySelector('.test')) {
               // Do something
               // Or maybe load another JS file dynamically
           }   
        }

})(jQuery, Drupal);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.