views:

748

answers:

4

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

+3  A: 

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.

Soufiane Hassou
Soufiane...good idea!
DA
+2  A: 

can you do:

$(".divToAppendTo:not(:has(span.myAppendedMarkup))");
Brandon H
This doesn't work
DEfusion
my bad. i had a typo.
Brandon H
I did try it hence the down vote, didn't notice the typo though, sorry.
DEfusion
+1  A: 

try

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

or

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

or

$("div.divToAppendTo").filter(function() { 
    return $(this).children('span.myAppendedMarkup').length == 0;  
});
Russ Cam
Russ. Thanks! And thanks for the variations, too.
DA
+1  A: 

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