0

I'm rewriting some stuff which I created with jQuery to vanilla JS. I can't find vanilla JS equivalent for mapping my function to all elements with specified CSS class. For example I have function for slider, in jQuery I'm mapping it like this:

(function($) {

    $.fn.slider = function() {
        this.each(function() {
            // Do some stuff
        });
    };

    $('.slider').slider();

}(jQuery));

What is the propper way to do it in vanilla JS?

2
  • 1
    You can choose document.querySelectorAll or document.getElementsByClassName, but the latter returns a HTMLCollection so it will not allow you to use NodeList.prototype.forEach(). Commented Nov 14, 2022 at 9:26
  • 2
    You might not need jQuery has a useful list of vanilla JS alternatives for jQuery functions Commented Nov 14, 2022 at 11:38

1 Answer 1

1

Implement e.g. a function initializeSlider which accepts an element-node parameter and do whatever has to be done with such a node.

Query a NodeList of all .slider classified element-nodes via e.g. querySelectorAll and execute the slider related function forEach of the node-list's node-items.

                                      // (function($) {
                                      //
                                      //   $.fn.slider = function() {
function initializeSlider(elmNode) {  //     this.each(function() {
  // Do some stuff with/to `elmNode`  //       // Do some stuff
}                                     //     });
document                              //   };
  .querySelectorAll('.slider')        //
  .forEach(initializeSlider);         //   $('.slider').slider();
                                      //
                                      // }(jQuery));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.