How do you go backwards through a chain using Jquery?

You are looking for the method end(). Just use it in place of goBackToParent().

Most of jQuery's DOM traversal methods operate on a jQuery object instance and produce a new one, matching a different set of DOM elements. When this happens, it is as if the new set of elements is pushed onto a stack that is maintained inside the object. Each successive filtering method pushes a new element set onto the stack. If we need an older element set, we can use end() to pop the sets back off of the stack.


You're looking for the end() method:

var a = $(this).parent().addClass('test').end()
               .children('selectorHere').text();

The method:

Ends the most recent filtering operation in the current chain and returns the set of matched elements to its previous state.

Update: based on your html snippet, you actually don't need end at all! The important thing about jQuery, is that most non-traversal methods return a copy of themselves - so if you call $(this).addClass('test'), you get a copy of $(this) back.

So for your snippet:

// does not work
var a = $(this)                       // points at #test
           .parent()                  // now refers to the tr which holds test
               .addClass('afb')       // still refers to the tr
               .end()                 // now we're back to #test
           .children('.selectMe')     // empty! there are no direct children of #test which match .selectMe
               .text();               // empty

Instead, try it without the end:

// works
var a = $(this)                       // points at #test
           .parent()                  // now refers to the tr which holds test
               .addClass('afb')       // still refers to the tr
           .children('.selectMe')     // found the .selectMe td
               .text();               // returns '1'

See .end()

Tags:

Jquery