Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if DOM element and children contains any text [JS or jQuery]

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 &#8203; 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?

like image 374
SimeriaIonut Avatar asked Dec 09 '15 17:12

SimeriaIonut


People also ask

How do I know if my DOM element has children?

HTML DOM Element hasChildNodes() The hasChildNodes() method returns true if the specified node has any child nodes, otherwise false.

How do you check if a element is present or not in DOM?

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

How do you check if an element is a child of a parent using JavaScript?

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.


1 Answers

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.

like image 79
SimplGy Avatar answered Nov 03 '22 00:11

SimplGy