Search code examples
javascriptjqueryjquery-chaining

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!


Solution

  • 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.