Please convert this jQuery code to Vanilla Javascript RRS feed

  • Question

  • User-1165293366 posted

    jQuery code is :

    $('.currency,.excludeCurrency').each(function () {
        new AutoNumeric(this, { allowDecimalPadding: "floats", modifyValueOnWheel: false });

    Thursday, September 6, 2018 10:35 AM

All replies

  • User753101303 posted


    Try https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/ that perhaps point to the issue you had when trying ?

    If you need further help please tell what you tried and what happens.

    Thursday, September 6, 2018 11:32 AM
  • User-893317190 posted

    Hi spidergrey.emad,

    You could write your code as follows.

     var cArray= document.getElementsByClassName("currency");
                 var eArray = document.getElementsByClassName("excludeCurrency");
                 Array.prototype.forEach.call(cArray, function (currentValue,index,arr) {
                        new AutoNumeric(currentValue, { allowDecimalPadding: "floats", modifyValueOnWheel: false });
                   Array.prototype.forEach.call(eArray, function (currentValue,index,arr) {
                      new AutoNumeric(currentValue, { allowDecimalPadding: "floats", modifyValueOnWheel: false });

    As you could see , it is  more complex than jquery. Because  javascript's forEach method couldn't apply to  dom array which is different from real array like [1,2,3].

    So you should use Array.prototype.forEach.call method to make the method apply to dom array. 

    If you are not familiar with  Function.prototype.call method , you will be confused.

    If so, please refer to mdn for more information about  Function.prototype.call and similar method Function.prototype.apply.


    One more thing , using raw javascript means you should deal with compatibility on your own.

    So some methods in javascript may not work in some browsers.

    Best regards,

    Ackerly Xu

    Friday, September 7, 2018 2:19 AM