Is there a jQuery selector/method to find a specific parent element n levels up?

JavascriptJqueryDomJquery Selectors

Javascript Problem Overview


Consider the following HTML. If I have a JSON reference to the <button> element, how can I get a reference to the outer <tr> element in both cases

<table id="my-table">
	<tr>
		<td>
			<button>Foo</button>
		</td>
		<td>
			<div>
				<button>Bar</button>
			</div>
		</td>
	</tr>
</table>

<script type="text/js">
	$('#table button').click(function(){
		//$(this).parent().parent() will work for the first row
		//$(this).parent().parent().parent() will work for the second row
		//is there a selector or some magic json one liner that will climb
		//the DOM tree until it hits a TR, or do I have to code this myself
		//each time?			
		//$(this).????
	});
</script>

I know I could special case each condition, but I'm more interested "however deep you happen to be, climb the tree until you find element X" style solution. Something like this, but more jQuery like/less-verbose

var climb = function(node, str_rule){
	if($(node).is(str_rule)){
		return node;
	}
	else if($(node).is('body')){
		return false;
	}
	else{
		return climb(node.parentNode, str_rule);
	}
};	

I know about the parent(expr) method, but from what I've seen is allows you filter parents one level up and NOT climb the tree until you find expr (I'd love code example proving me wrong)

Javascript Solutions


Solution 1 - Javascript

The parents function does what you want:

$(this).parents("tr:first");

Solution 2 - Javascript

Also, if you are using jQuery 1.3+ you can use the closest method

$(this).closest("tr");

Solution 3 - Javascript

not jQuery but this options works much better

node.contains( otherNode )

> The Node.contains() method returns a Boolean value indicating whether > a node is a descendant of a given node or not

https://developer.mozilla.org/en/docs/Web/API/Node/contains

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlan StormView Question on Stackoverflow
Solution 1 - JavascriptSebView Answer on Stackoverflow
Solution 2 - JavascriptbendeweyView Answer on Stackoverflow
Solution 3 - JavascriptzloctbView Answer on Stackoverflow