How to get elements which have no children, but may have text?

前端 未结 3 1738
夕颜
夕颜 2021-01-01 19:09

the empty selector says that: Matches all elements that have no children (including text nodes).
Finds all elements that are empty - they don\'t have child elements or t

3条回答
  •  死守一世寂寞
    2021-01-01 20:00

    I made a pure JavaScript function for anyone that does not want to use jQuery.

    const getElementsWithNoChildren = (target) => {
        let candidates;
    
        if (target && typeof target.querySelectorAll === 'function') {
            candidates = target.querySelectorAll('*');
        }
        else if (target && typeof target.length === 'number') {
            candidates = target;
        }
        else {
            candidates = document.querySelectorAll('*');
        }
    
        return Array.from(candidates).filter((elem) => {
            return elem.children.length === 0;
        });
    };
    

提交回复
热议问题