Using jQuery NOT selector to exclude elements with particular children.
I have a function that appends some HTML to an element. It may get called more than once, so I only want it to append the HTML 开发者_JAVA技巧to elements that haven't already had the HTML added.
Example:
<div class="divToAppendTo"></div>
<div class="divToAppendTo"><span class="myAppendedMarkup"></span></div>
As such, I'd like to select all .divToAppendTo that don't have an immediate child of .myAppendedMarkup
My stab at it doesn't seem to work:
$(".divToAppendTo:not(>span.myAppendedMarkup)")
It always appends when I call it (thereby duplicating the content).
try
$("div.divToAppendTo:not(:has(span.myAppendedMarkup))")
or
$("div.divToAppendTo").filter(function() {
return $(this).children('span.myAppendedMarkup').length == 0;
});
If you don't mind, I think I may have an easier solution for what you're trying to do.
Whenever you append HTML to a .divToAppendTo
do a $(this).removeClass("divToAppendTo");
this way you'll just need to select .divToAppendTo
while being sure that it doesn't have any code appended to it.
If you are using this class for something else, you can always use another one to do this.
can you do:
$(".divToAppendTo:not(:has(span.myAppendedMarkup))");
I like this for its readability, and it's comparable in efficiency to the fastest suggestion in other answers.
var completeSet = $( "div.divToAppendTo" );
var unwantedSet = completeSet.has( "span.myAppendedMarkup" );
var wantedSet = completeSet.not(unwantedSet);
If you don't need to leave the className in place go for Soufiane's answer, otherwise this should work:
$('div.divToAppendTo').filter(function() {
return $(this).html() == '';
}) );
Or if you expect some other HTML in the .divToAppendTo
's, then use this:
$("div.divToAppendTo").filter(function() {
return $(this).children('span.myAppendedMarkup').length == 0;
});
精彩评论