Jquery – Override core jQuery functions on Element level

coreelementfunctionjqueryoverriding

Is it possible to override core jQuery functions on Element level, so for an example, i want to override val() function only on one <select> element.

if i do something like this

var element = $('select');
var old_val = element.val;
element.val = function () {
  console.log('The new val');
  return old_val.apply(this, arguments);
}
element.val(19);

it works as expected, but as soon as i address the same field with new jQuery instance

var element = $('select');
element.val(19);

it stops working because we have new instance of jQuery object. if i fiddle with $.fn.val function i change that behavior for all objects who support val function, which is a bit to much for me.

Any help will be appreciated.
Thank you.

Best Solution

I made this jquery extension for doing just what you're talking about:

// overrides a method thats supposed to be called on a single node (a method like val)
$.fn.overrideNodeMethod = function(methodName, action) {
    var originalVal = $.fn[methodName];
    var thisNode = this;
    $.fn[methodName] = function() {
        if (this[0]==thisNode[0]) {
            return action.apply(this, arguments);
        } else {
            return originalVal.apply(this, arguments);
        }
    };
};

Bonus over Dave's answer - you don't have to pollute the jquery data namespace or worry about someone overwriting that key