댓글 검색 목록

[javascript] 요소가 다른 요소의 자손인지 확인 (8/86)

페이지 정보

작성자 운영자 작성일 20-03-31 12:41 조회 843 댓글 0

자식 요소가 부모 요소의 자손인지 알아 내고 싶다고 가정하자.


https://htmldom.dev/check-if-an-element-is-a-descendant-of-another 


1. contains 메소드를 사용하십시오. 


const isDescendant = parent.contains(child);

2. 부모를 볼 때까지 아이에게서 올라가십시오 


// Check if `child` is a descendant of `parent`
const isDescendant = function(parent, child) {
    let node = child.parentNode;
    while (node) {
        if (node === parent) {
            return true;
        }

        // Traverse up to the parent
        node = node.parentNode;
    }

    // Go up until the root but couldn't find the `parent`
    return false;
};

댓글목록 0

등록된 댓글이 없습니다.

웹학교 로고

온라인 코딩학교

코리아뉴스 2001 - , All right reserved.