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开发者_如何学Python 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
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
$('span:empty').css('background-color','red');
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>
精彩评论