So you need either .closest() or .parents() as shown below.
var target = $('#source').closest('#target'); var target = $('#source').parents('#target'); alert ( target[0].id );
HTML example for the above:
<div id="target"> Man! <div> <div> <div id="source"></div> </div> </div> </div>
I would recommend .closest() , because .parents() moves the DOM tree to the root element of the document, adding each ancestor element to a temporary collection; it then filters this collection based on the selector if supplied, while .closest() moves through the DOM tree only until it finds a match for the supplied selector.
Edit:
As for your case, you may want to do:
var n = 5; //say you want the 5th parent var parent5th = $("#source").parents().eq(n-1); alert (parent5th[0].id); //So, your code becomes: var n = 8; //You want the 8th parent $(e).parents().eq(n-1);
Here is a not-so-ugly function if you:
$.fn.nthParent = function(level) { level = level || 1; if (level <= 0) return; return level === 1 && $(this).parent() || $(this).parents().eq(level-1); }
Using:
//Apply some CSS to level 1 (immediate) parent $("#source").nthParent().css({ border: "1px solid red" }); OR $(".source").each(function(i) { $(this).nthParent(i+1).css({ border: "4px solid blue" }); });
Demo for the above.
source share