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.
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.
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).
$("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.
Use filter
to filter those elements that don’t have textual contents:
$('#layer6 > span.col').filter(function(){ return $(this).text().trim() != ""; }).length
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