Find if the element contains x but not y (jQuery)
문제
<div>
<p><a href="#">link</a> some text</p>
<p><a href="#">link</a></p>
<p><a href="#">link</a> some text</p>
<p><a href="#">link</a></p>
</div>
I want to find (and addClass to) the <p>
tags that DO NOT contain text, directly inside itself or its children.
해결책
This works fine, I did have to empty the text out of one of your paragraphs to test:
var $eles = $('p').filter(function() {
return $(this).text().length == 0;
});
$eles.addClass("foo");
다른 팁
I suppose You have an error in the problem description, as the a tag always contains text in the example.
As far as I know there is no standard selector allowing to check if there is a direct content, but You could try this:
$('p').each(function(){
var p = $(this).clone();
p.children().remove();
if(p.text().length){
$(this).addClass('gotcha');
}
});
Should work if You wish to check only the paragraph insides.
제휴하지 않습니다 StackOverflow