[jQuery] Function: $(...).ancestorsTo(match)
I wrote a method that will provide a list of ancestors for any number of generations until an ancestor matches the expression. Example:
<span style="font-weight: bold;">BODY</span>
<span style="font-weight: bold;">
DIV</span>
<span style="font-weight: bold;">UL</span>.myClass
<span style="font-weight: bold;">LI</span>
<span style="font-weight: bold;">UL</span>
<span style="font-weight: bold;">
LI</span> #myId
<span style="font-weight: bold;">$('#myId').ancestors()</span>
returns [UL, LI, UL.myClass, DIV, BODY]
<span style="font-weight: bold;">$('#myId').ancestors("UL.myClass")</span>
returns [UL.myClass]
Returns all elements up to and including the match expression
<span style="font-weight: bold;">$('#myId').ancestorsTo("UL.myClass")</span>
returns [UL, LI, UL.myClass]
Code:
jQuery.fn.ancestorsTo = function(match) {
var j = $();
var b = false;
$(this[0]).ancestors().each(function() {
if (b == false) {
j.add(this);
if ($(this).is(match)) {
b = true;
}
}
});
return j;
};
Cheers,
-js
_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/