I thought there was something in jquery that allowed you go backward through a chain.
I want to do this:
var a = $(this).parent().addClass('test').goBackToParent().children('selectorHere').text()
I want to get the parent of the object that I have and add a class name to it. Once I do that I want to go through its children and find a child that matches my selector and get its text.
Can I do this, or do I have to do this instead:
$(this).parent().addClass('test');
var a = $(this).parent().children('selectorHere').text()
Edit
I am using "end" now but it does not work I made an example that you can try here
<table>
<th>
<tr>one</tr>
<tr>two</tr>
</th>
<tr>
<td id="test"><a href="#"><img src="http://ais.web.cern.ch/ais/apps/hrt/SMT%20v2/Images/btnbar_edit.png" /></a></td>
<td class="selectMe">1</td>
</tr>
</table>
$(function() {
$('#test').click(function() {
// does not work
var a = $(this).parent().addClass('afb')
.end().children('.selectMe').text();
// works
var b = $(this).parent().children('.selectMe').text();
alert(a + ' -should have value');
alert(b + ' -works');
return false;
});
});
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'
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.