Mathias Bynens
Mathias Bynens

Reputation: 149594

How to improve this code using $(this) in jQuery?

I have the following jQuery function (simplified):

function doSomething(el, str) {
 el.find('.class').text(str));
}

Don't worry about the .text() part, in reality I'm doing something a bit more complicated than that... But since that's irrelevant to my question, I'm just using .text() here as a simple example.

The problem is, everytime I'm calling the doSomething() function, the code looks like this:

doSomething($(this), foo); // the second argument is irrelevant
doSomething($(this), bar); // the second argument is irrelevant

As you can see, I'm always passing $(this) as the first argument. Somehow I feel this is not the way to go... Can this function be improved so it automatically inherits the $(this) from the context where it's called? Maybe something like the following:

$(this).doSomething(foo); // the foo argument is irrelevant
$(this).doSomething(bar); // the bar argument is irrelevant

Upvotes: 2

Views: 131

Answers (2)

redsquare
redsquare

Reputation: 78667

You can create a simple plugin to do this.

Lots of articles about. See this one on the jQuery site for more info

$(function(){

   jQuery.fn.changeAnchorText = function(str) {
     return this.each( function(){
        $(this).find('a.someClass').text(str);
     });
   };

});

then to invoke it

$('div').changeAnchorText("Any descendant anchor tags inside this div with a class of someClass will have the text changed to this message");

Upvotes: 3

Anwar Chandra
Anwar Chandra

Reputation: 8648

seems you want something that works like jquery plugin.

(function($){

//Attach doSomething method to jQuery
$.fn.extend({ 

      doSomething: function(options) {

        return this.each(function() {

          var el = $(this);
          // do something here

        });
    }
});

})(jQuery);

Upvotes: 1

Related Questions