maximus
maximus

Reputation: 2437

How to create elements and select them on the fly with jQuery

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!

Upvotes: 3

Views: 410

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

$('<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

Upvotes: 2

pimvdb
pimvdb

Reputation: 154818

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.

Upvotes: 3

Related Questions