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).
To exclude first and second element from jQuery, use the slice() method.
The not() is an inbuilt function in jQuery which is just opposite to the filter() method. This function will return all the element which is not matched with the selected element with the particular “id” or “class”. Syntax: $(selector).not(A) The selector is the selected element which is not to be selected.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With