DOM / pure JavaScript solution to jQuery.closest() implementation?

后端 未结 8 1877
感动是毒
感动是毒 2020-12-06 00:26

Here\'s the markup i\'m trying to query. So given the markup:

8条回答
  •  盖世英雄少女心
    2020-12-06 01:14

    In this case, use JavaScript's closest()

    Exemple:

    var el = document.getElementById('div-03');
    
    var r1 = el.closest("#div-02");  
    // returns the element with the id=div-02
    
    var r2 = el.closest("div div");  
    // returns the closest ancestor which is a div in div, here is div-03 itself
    
    var r3 = el.closest("article > div");  
    // returns the closest ancestor which is a div and has a parent article, here is div-01
    
    var r4 = el.closest(":not(div)");
    // returns the closest ancestor which is not a div, here is the outmost article
    Here is div-01
    Here is div-02
    Here is div-03

    You can find more information, on MDN Web Docs by clicking here

提交回复
热议问题