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

前端 未结 3 1721
夕颜
夕颜 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 19:46

    Get any element that doesn't have any other element:

    $('*:not(:has(*))');
    
    0 讨论(0)
  • 2021-01-01 19:59

    If an element has only text, children() will have a length of 0:

    <div id="test1">
    Hello World
    </div>
    
    <div id="test2">
    <b>Hey there</b>
    </div>
    
    <script>
    alert($("#test1").children().length); // alerts 0
    alert($("#test2").children().length); // alerts 1 (the bold tag)
    </script>
    

    EDIT: In response to your edit, jQuery is awesome enough to let you do custom filters:

    $.expr[':'].emptyOrText = function(e) {  
        return $(e).children().length == 0;
    };
    

    So, using the above against the HTML above, you could do this:

    $('div:emptyOrText'); // will select #test1
    
    0 讨论(0)
  • 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;
        });
    };
    
    0 讨论(0)
提交回复
热议问题