how to change the arguments when extending a jQuery function

When I modify the arguments of html() I get an error that I can't figure out.

In this example I'm just stringifying and then parsing, and it causes the same error:

(function($) {
    var oldhtml = $.fn.html;
    $.fn.html = function() {
        var args = JSON.stringify(arguments);
        // do some stuff with args
        args = JSON.parse(args);
        var ret = oldhtml.apply(this, args);
        return ret;
    };
})(jQuery);

Getting this error:

jquery-ui.min.js:5 Uncaught TypeError: e(...).addClass(...).html(...).appendTo is not a function

Answers 1

  • The problem is your use of JSON.stringify(), since arguments is not a Array object, it will parse it like an key/value object with indexes. So after parsing args is no longer an array, instead it is an object.

    So a possible solution is convert arguments to an array, then stringify it

    (function($) {
      var oldhtml = $.fn.html;
      $.fn.html = function() {
    
        $('#args-strinfigy').text(JSON.stringify(arguments)); //see this
    
        var args = JSON.stringify([].slice.call(arguments)); //or JSON.stringify(Array.from(arguments))
        // do some stuff with args
        args = JSON.parse(args);
        var ret = oldhtml.apply(this, args);
        return ret;
      };
    })(jQuery);
    
    $('div').html('asdfasd').appendTo('body')
    div {
      background-color: grey;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p></p>
    <div>
    </div>
    
    <pre id="args-strinfigy"></pre>


Related Articles