How to find first parent element in jquery

前端 未结 3 748
情歌与酒
情歌与酒 2021-02-14 05:33

Conside below html -

相关标签:
3条回答
  • 2021-02-14 06:13

    just use

    $(".element").closest('#container1');
    

    if no ancestor with that id is found then

    $(".element").closest('#container1').length will be 0

    0 讨论(0)
  • 2021-02-14 06:16
    $(".element").parents();
    

    will give all parents of .element(including html and body)

    DEMO

    To find any specific parent, suppose container1 then

    $('.element').parents('.container1')
    

    DEMO

    jQuery .parents() generally find all parents, but if you passed a selector then it will search for that.

    0 讨论(0)
  • 2021-02-14 06:21

    To get the first parent personally I use the following construction:

    var count_parents = $(".element").parents().length;
    $(".element").parents().eq(count_parents - 1);
    

    Hope, it will be helpful for someone.

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