tags:

views:

324

answers:

3

jQuery is pretty much a big selector transversing engine with useful stuff hung on it. With all that power I can't believe there is not a way to jump around a chain. Therefore I'm assuming I am ignorant in the manner of accomplishing this.

I want to be able to fork a chain in order to make a modification, and then return to the root chain.

Example:

$('#clone-container')
    .clone()
    .find('#clone-topic')         // fork
        .attr('id', 'new-topic')
                                  // return to root chain (how?)
    .find('#clone-body')          // fork
        .attr('id', 'new-body')
    .attr('id', 'new-container')  // return to root chain (how?)
    .append('body');

I hope that made at least a little bit of sense. :)

Any help would be appreciated.

Thanks.

+3  A: 

use .end()

Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state (right before the destructive operation).

redsquare
But can end() be called several times? Or are we locked into only one revert level?
Spot
Yes, multiple times.
David Toso
Multiples work also
redsquare
Ahh, thank you!
Spot
No problem. Enjoy
redsquare
+1  A: 

You can use:

$('#clone-container')
.clone()
.find('#clone-topic')         // fork
    .attr('id', 'new-topic')
    .end()  // return to root chain
.find('#clone-body')          // fork
    .attr('id', 'new-body')
.attr('id', 'new-container')
.end()  // return to root chain
.append('body');
Cide
+1  A: 

You could use end(), but I think that is pushing the whole chaining thing a bit too far...

I think this would be the most readable way to do what you want:

var $c = $('#clone-container').clone();
$('#clone-topic', $c).attr('id', 'new-topic');
$('#clone-body', $c).attr('id', 'new-body');
$c.attr('id', 'new-container').append('body');

But to each their own. :)

Paolo Bergantino