Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 727
Amr Elgarhy Avatar asked Apr 13 '09 14:04

Amr Elgarhy


People also ask

How do you check if an element has a child?

To check if an HTML element has child nodes, you can use the hasChildNodes() method. This method returns true if the specified node has any child nodes, otherwise false . Whitespace and comments inside a node are also considered as text and comment nodes.

How do I get text from an element?

Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.


3 Answers

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

$('*:not(:has(*))');
like image 165
Borgar Avatar answered Sep 19 '22 13:09

Borgar


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
like image 33
Paolo Bergantino Avatar answered Sep 17 '22 13:09

Paolo Bergantino


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;
    });
};
like image 42
Seth Holladay Avatar answered Sep 21 '22 13:09

Seth Holladay