jQuery: selecting grandparents

后端 未结 6 1084
悲哀的现实
悲哀的现实 2020-12-14 05:39

Is there a better way to select grandparent elements in jQuery in order to avoid this ?

$(this).parent().parent().parent().parent().parent().children(\".titl         


        
6条回答
  •  余生分开走
    2020-12-14 06:03

    @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

提交回复
热议问题