javascriptjqueryjquery-pluginsinitializationselectors-api

How to map function on each element with css class in javascript


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?


Solution

  • 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));