Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, find if element has any text

Tags:

jquery

text

I am dealing with some generated spans and I would like to find which one of them does not contain any text.

The markup is:

<span id="layer6">     <span class="drag col">  Some text</span>     <span class="drag col">  More text</span>     <span class="drag col">  </span>     <span class="drag col">  I also have text</span> </span> 

I can get get the ones that have "some text" with this code but I can not get the empty ones:

if ($('#layer6 > span.col:contains("some text")').length > 0) {     alert ("I have text"); } 

How to get the empty ones? I am thinking in using .length to do it but I did not manage.

like image 282
Mircea Avatar asked Mar 04 '10 10:03

Mircea


People also ask

How do I check if a div contains a text?

To check if a div element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.

How to find contains in jQuery?

jQuery :contains() SelectorThe :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).


2 Answers

$("span.col").each(function(){     if (!$(this).text().trim().length) {         $(this).addClass("foo");     } }); 

http://jsfiddle.net/cfgr9/1/

Obviously instead of adding a class you can do as you like, return the object etc

UPDATE: Removed strange hidden character after final semicolon that caused js error.

like image 72
Alex Avatar answered Sep 28 '22 05:09

Alex


Use filter to filter those elements that don’t have textual contents:

$('#layer6 > span.col').filter(function(){     return $(this).text().trim() != ""; }).length 
like image 31
Gumbo Avatar answered Sep 28 '22 03:09

Gumbo