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 want is to get elements which has no children but may have text inside., how?



UPDATE:
Example:
I want select these elements which has no children but may have text, with syntax like this:

$('div:empty, a:empty, span, p:empty, td:empty, img, input').mousemove(myMouseOverHandler);

Answers:

Answer

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

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

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
Answer

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;
    });
};

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.