jQuery,查找元素是否有任何文本 [英] jQuery, find if element has any text

查看:63
本文介绍了jQuery,查找元素是否有任何文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些生成的跨度,我想找出其中一个不包含任何文本.

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

标记为:

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

如何获取空的?我正在考虑使用.length来做到这一点,但是我没有做到.

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

推荐答案

$("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

更新:删除了导致js错误的最后一个分号后的奇怪的隐藏字符.

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

这篇关于jQuery,查找元素是否有任何文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆