Skip to content Skip to sidebar Skip to footer

How To Get Elements Which Have No Children, But May Have Text?

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 text. What i w

Solution 1:

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

$('*:not(:has(*))');

Solution 2:

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

<divid="test1">
Hello World
</div><divid="test2"><b>Hey there</b></div><script>alert($("#test1").children().length); // alerts 0alert($("#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

Solution 3:

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

constgetElementsWithNoChildren = (target) => {
    let candidates;

    if (target && typeof target.querySelectorAll === 'function') {
        candidates = target.querySelectorAll('*');
    }
    elseif (target && typeof target.length === 'number') {
        candidates = target;
    }
    else {
        candidates = document.querySelectorAll('*');
    }

    returnArray.from(candidates).filter((elem) => {
        return elem.children.length === 0;
    });
};

Post a Comment for "How To Get Elements Which Have No Children, But May Have Text?"