Adam Kiss
Adam Kiss

Reputation: 11859

Use jQuery .find() result as argument in callback function in chain

I have this problem (is it now?):

Let's have this HTML:

<div>
 <p></p>
 <p id="bar"></p>
</div>
<div>
 <p id="foo"></p>
 <p id="baz"></p>
</div>

simple.

In jQuery, we have function (e.g. 'click') added to all divs:

$('div').click(function(){
  $(this).doSomething($(this))
  .find('#baz')
    .doSomethingWithCallback ({args}, callbackFunction($FIND_RESULT) );
});

Obviously, variable $FIND_RESULT doesn't exist – I would like to know how can I get to result of last .find() query?

Is there any way, or do I have to break my mad chain (or repeat $(this).find() as argument)?

Edit: IRL example:

function hide($div) { $div.css({'display': 'none'});

function ...
  $(this)
    .anyFunction()
  .find('.foo')
    .animate({opacity: 0}, 250, hide(^that^));
 }

Upvotes: 2

Views: 3031

Answers (3)

qwertymk
qwertymk

Reputation: 35276

Are you looking for jQuery's

end()

?

If you're making you own plugins then take a look at pushSack() and end()

function ...
  $(this)
    .anyFunction()
  .find('.foo')
  .end()  // <---
    .animate({opacity: 0}, 250, hide(^that^));
 }

Upvotes: 0

rkw
rkw

Reputation: 7297

I'm a bit confused also. The .find() method is extremely robust, so are all the other jQuery functions. Each one executes on a group of elements and then passes those elements back so that other functions can chain on them. http://jsfiddle.net/rkw79/DXbXU/

On your custom function, are you returning the objects after you process them? http://docs.jquery.com/Plugins/Authoring#Maintaining_Chainability

Upvotes: 0

Sergi Ram&#243;n
Sergi Ram&#243;n

Reputation: 1744

Generally with jQuery functions, your doSomethingWithCallback will be executed multiple times one for each match of find(), and therefore your callback method will be called one time for each match too, so passing the set of elements is innecesary, use $(this).

Upvotes: 1

Related Questions