2011-02-05 2 views
2

내가 원하는 어떤 텍스트 노드가없는 경우는 <img />이 포함되어 있지만 텍스트 문자열을 포함하지 않는 경우에만 jQuery를가 <a>diog-failclass을 추가 , 또는 텍스트 문자열을 포함하는 다른 HTML 요소. 2 개의 예는 다음과 거짓 같습니다jQuery를 : 그것은 이미지를 포함하는 요소에 클래스를 추가하지만,

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

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

다음 예제는 jQuery를이 classdiog-fail의 적용 것이다 :

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

중요 : 텍스트의 문자열 아무것도 될 수 있습니다.

답변

8

간단히 .text()을 사용하여 앵커의 모든 텍스트를 결합 (마크 업 무시)하기 만하면됩니다. 그런 다음 $.trim 수 있으며 길이를 테스트합니다. 길이 제로의 .text()와 요소에 .diog-fail 클래스를 추가 :

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

Try it here.

+0

최고, 않습니다 내가 필요 정확히! 감사. – DigiKev

+0

+1 : 멋진 솔루션! – naveen

+0

@DigiKev - 천만에요. @yetanothercoder - 감사합니다! – karim79

관련 문제