JQuery find first parent element with specific class prefix

后端 未结 2 1729
小鲜肉
小鲜肉 2020-12-12 17:53

I want to get the first parent which has a specific class prefix, suppose:

相关标签:
2条回答
  • 2020-12-12 18:31

    Jquery later allowed you to to find the parents with the .parents() method.

    Hence I recommend using:

    var $div = $('#divid').parents('div[class^="div-a"]');
    

    This gives all parent nodes matching the selector. To get the first parent matching the selector use:

    var $div = $('#divid').parents('div[class^="div-a"]').eq(0);
    

    For other such DOM traversal queries, check out the documentation on traversing the DOM.

    0 讨论(0)
  • 2020-12-12 18:33

    Use .closest() with a selector:

    var $div = $('#divid').closest('div[class^="div-a"]');
    
    0 讨论(0)
提交回复
热议问题