2

Say that I have two html nodes like this:

<div class='node a'>one</div>
<input class='node b' value='two'>

and I'd like to add a method for $('.node.a'), but not for node b. What I'd really like to do is something like this:

$('.node.a').addMethod('val', function() {
  return $('.node.b').val();
});

alert($('.node.a').val()); // alerts 'two'

Clearly I don't want to override the 'val' method for every jQuery node. Is it possible to do this?

* UPDATE *

As per mgibsonbr's suggestion, I wrote a jQuery plugin to do this for me. Instead of using jQuery data method, I only run different functionality if the node in question is the one being called. This means that this form will not work for jquery lists that match multiple html nodes. Here it is:

// 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);
        }
    };
};
B T
  • 57,525
  • 34
  • 189
  • 207
  • You *could* overload the `val()` to do this different behaviour if you wanted to. – alex Jan 26 '12 at 23:23
  • 1
    Is there a particular reason you aren't putting an ID attribute on the elements and just directly referencing the one you want? – JohnFx Jan 26 '12 at 23:25
  • Yes, because this is obviously a trivial example, and not exactly what I'm doing. I'm writing a plugin to transform a
    – B T Jan 26 '12 at 23:38