tags:

views:

167

answers:

3

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.

+2  A: 

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

$('#layer6 > span.col').filter(function(){
    return $(this).text().trim() != "";
}).length
Gumbo
This should work, please let me try it and I'll post the results. Thanx
Mircea
+1  A: 

i'm not aware of such a selector, but it's easy to write

jQuery.expr[':'].empty = function(obj) { return jQuery(obj).text().replace(/^\s+|\s+$/, "").length == 0; }

jQuery.expr[':'].hasNoText = function(obj) {
    return jQuery.trim(jQuery(obj).text()).length == 0;
}

and then, for example

$("#layer6 span:hasNoText").text("NEW TEXT")

just for googlers' benefit, here's the extended version. $("node:matches(/regexp/)") selects nodes whose text content matches given regexp.

    <script>
    /// :matches(regexp)    
    /// regexp is like js regexp except that you should double all slashes
    jQuery.expr[':'].matches = function(obj, index, args) {
        var m = (args[3] + "").match(/^\/(.+?)\/(\w*)$/);
        var re = new RegExp(m[1], m[2]);
        return jQuery(obj).text().search(re) >= 0;
    }
    </script>

demo:

    <script>
    $(function() {
        $("div").click(function() {
            $("div:matches(/foobar/)").text("foobar was here")
            $("div:matches(/foo\\s+bar/i)").text("some text")
            $("div:matches(/^\\s+$/)").text("only spaces")
        });
    });
    </script>

    html before 

    <div>foobar</div>
    <div>Foo Bar</div>
    <div>       </div>

    html after 

    <div>foobar was here</div>
    <div>some text</div>
    <div>only spaces</div>
stereofrog
:empty exists: http://api.jquery.com/empty-selector/
D_N
yeah, my bad...
stereofrog
thanx for the suggestion, I will try this and let you know
Mircea
:empty gets the element with absolutly no text, content. In my case I have 2 empty spaces between spans:<span class="drag col"> </span>
Mircea
+2  A: 
$("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

Alex
Thanx Alex, this works. There is an illegal character after your last });​ but i had removed that and it works fine.Thanx
Mircea