开发者

jQuery: Adding a class to an element when it contains an image, but only if there are no text nodes

I want jQuery to add a class of diog-fail to an <a> when it contains an <img /> but does not contain a string of text, or another HTML element that contains a string of text. The 2 examples below would be false:

<a href="#">
    <img width="100" height="100" alt="alternative text" src="some/location/image.gif" />
    Some text
</a&开发者_如何学JAVAgt;

<a href="#">
    <img width="100" height="100" alt="alternative text" src="some/location/image.gif" />
    <span>Some text</span>
</a>

The following example would have jQuery apply the class of diog-fail:

<a href="#">
    <img width="100" height="100" alt="alternative text" src="some/location/image.gif" />
</a>

Important: The string of text could be anything.


Simply use .text() to grab out a concatenation of all the text in the anchor (ignoring markup). You can then $.trim it and test the length. Add the .diog-fail class to elements with zero-length .text():

$("a:has(img)").filter(function() {
   return !$.trim($(this).text()).length; 
}).addClass("diog-fail");

Try it here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜