Is there a better way to select grandparent elements in jQuery in order to avoid this ?
$(this).parent().parent().parent().parent().parent().children(\".titl
@Femi had an answer to do this, and mentioned recursion, yet his solution was not recursive, here's a recursive jQuery solution for getting ancestors of an item:
$.fn.gparent = function( recursion ){
console.log( 'recursion: ' + recursion );
if( recursion > 1 ) return $(this).parent().gparent( recursion - 1 );
return $(this).parent();
};
If this is your HTML:
child
You can call
console.log( $('#child').gparent( 2 ) );
to get the grandparent of element child. Here's the JSFiddle