Check if any ancestor has a class using jQuery

crmpicco picture crmpicco · Jun 13, 2013 · Viewed 130.7k times · Source

Is there any way in jQuery to check if any parent, grand-parent, great-grand-parent has a class.

I have a markup structure that has left me doing this sort of thing in the code:

$(elem).parent().parent().parent().parent().hasClass('left')

However, for code readability i'd like to avoid this sort of thing. Is there any way to say "any parent/grandparent/great-grand-parent has this class"?

I am using jQuery 1.7.2.

Answer

Alex picture Alex · Jun 13, 2013
if ($elem.parents('.left').length) {

}