DA.
DA.

Reputation: 40671

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 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).

Upvotes: 16

Views: 15434

Answers (5)

Joffer
Joffer

Reputation: 1939

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);

Upvotes: 2

Russ Cam
Russ Cam

Reputation: 125488

try

$("div.divToAppendTo:not(:has(span.myAppendedMarkup))")

or

$("div.divToAppendTo").filter(function() { 
    return $(this).children('span.myAppendedMarkup').length == 0;  
});

Upvotes: 17

Brandon Henry
Brandon Henry

Reputation: 3720

can you do:

$(".divToAppendTo:not(:has(span.myAppendedMarkup))");

Upvotes: 5

DEfusion
DEfusion

Reputation: 5613

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;  
});

Upvotes: 1

Soufiane Hassou
Soufiane Hassou

Reputation: 17750

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.

Upvotes: 5

Related Questions