Find parent and first child of it's parent

前端 未结 4 1328
無奈伤痛
無奈伤痛 2021-02-19 23:44

I am trying to find the parent of an element and it\'s parent first child, the code is like this:

        
  • &l
相关标签:
4条回答
  • 2021-02-20 00:10

    There is no need of total traversing back to the parent one after the other in a hierarchy, you can just do use parents() instead of parent() in this way

    $('.selected').parents('ul.lowerMenu').children(:first-child').addClass('selected');
    

    Try it this is working!!

    0 讨论(0)
  • 2021-02-20 00:13

    If you go up two levels, then find the next child, you're only going down one level -- you're setting the selected class on the <li>, not the <a> below it.. You need to go down another level. So it should be:

    $('.selected').parent().parent().children(':first-child').children().addClass('selected');
    

    Another way to get there is:

    $('.selected').parent().siblings(':first-child').children().addClass('selected');
    
    0 讨论(0)
  • 2021-02-20 00:15
    $('.selected').parent().siblings(':first-child').children().addClass('selected');
    

    FIDDLE DEMO

    0 讨论(0)
  • 2021-02-20 00:19
    $('.selected').closest('ul').find('li:first').addClass('selected');
    

    reference closest

    0 讨论(0)
提交回复
热议问题