Check if class exists somewhere in parent - vanilla JS

前端 未结 10 844
时光说笑
时光说笑 2020-12-09 08:42

I\'m really struggling to see how to do this. I want to check if a class exsits somewhere in one of the parent elements of an element.

I don\'t want to use any libra

10条回答
  •  被撕碎了的回忆
    2020-12-09 09:05

    You can use the closest() method of Element that traverses parents (heading toward the document root) of the Element until it finds a node that matches the provided selectorString. Will return itself or the matching ancestor. If no such element exists, it returns null.

    You can convert the returned value into boolean

    const el = document.getElementById('div-03');
    
    const r1 = el.closest("#div-02");  
    console.log(Boolean(r1));
    // returns the element with the id=div-02
    
    const r2 = el.closest("#div-not-exists");
    console.log(Boolean(r2));
    Here is div-01
    Here is div-02
    Here is div-03

提交回复
热议问题