3

I'm a bit stumped with this. I would like to create some elements (using jQuery), call a function on that wrapped set, and continue this process several times via a chain. For example,

$('<div id="xxx"></div>')
  .call_plugin()
  .append('<div id="yyy"></div>')
  .call_plugin()
  .etc...
.end();

Where the first call to plugin affects xxx, the second affects yyy, and so forth. But this isn't happening; I think the call_plugin() is being called on the first div (id=xxx) every time. Is there a workaround?

Thanks in advance!

maximus
  • 2,417
  • 5
  • 40
  • 56
  • .append() actually "pastes" yyy insdes xxx, and returns the new xxx. So the second call_plugin affects the new xxx. – roselan Oct 31 '11 at 22:37

2 Answers2

3

Call jQuery again for other elements to execute certain functions on, and append those with .append:

$('<div id="xxx"></div>')
  .call_plugin()
  .append(
     $('<div id="yyy"></div>')
     .call_plugin()
  );

You can nest them the same way:

$('<div id="xxx"></div>')
  .call_plugin()
  .append(
     $('<div id="yyy"></div>')
     .call_plugin()
     .append(
        $('<div id="zzz"></div>')
        .call_plugin()
     )
  );

Just don't forget not to put ;s after the nested appends.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
2
$('<div id="xxx"></div>')
  .call_plugin()
  .append('<div id="yyy"></div>')
  .find('#yyy') // added this. From now on the current selection is #yyy element
  .call_plugin(); // this will be called on #yyy

The .end() method (that you use at the end) is used to end the current selection in a chain if you want to continue with the previous one of the same chain...

In your example

$('<div id="xxx"></div>')
  .call_plugin()
  .append('<div id="yyy"></div>')
  .find('#yyy') // added this. From now on the current selection is #yyy element
  .call_plugin() // called on #yyy
  .end() // this returns the selection to be #xxx
  .something()//something else that will be called on #xxx
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • This was a tough call. I think this answer is simpler, but I just couldn't get it to work. (Doesn't mean it's wrong either!) +1, and thank you for the reply! – maximus Oct 31 '11 at 23:19