I want to be able to check if an element contains any text inside of it. I want to be able to remove the element if there isn't any text in it.
However, this dom element might contain a children, or more, and those children might contain other children as well. So I want to be able to follow the dom tree of the element and search through all of the elements inside it for text.
Something like this:
<div id="myElement">
<span></span>
<span></span>
<span>
<span></span>
<span>b</span>
</span>
</div>
Now the div directly doesn't have any text, however it's children have. How can I check if there is any text in the whole div?
Edit:
Apparently I have a ​
character in one of the spans, which I know is a zero width white-space. So basically even though there is no text, the jQuery text() finds it as one and returns false.
How do I get around that?
HTML DOM Element hasChildNodes() The hasChildNodes() method returns true if the specified node has any child nodes, otherwise false.
contains DOM API, you can check for the presence of any element in the page (currently in the DOM) quite easily: document. body. contains(YOUR_ELEMENT_HERE);
The Node. contains() method is used to check if a given node is the descendant of another node at any level. The descendant may be directly the child's parent or further up the chain.
None of these answers use innerText
, which might be the simplest.
innerText
gets the rendered text of the current node and all descendants.
So to check if your node's subtree has any text in it, you can use this one liner:
myNode.innerText.trim() === '';
If this expression evaluates true, there's no text in myNode
or its children.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With