Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 852
DA. Avatar asked Nov 13 '09 17:11

DA.


People also ask

How to exclude selector in jQuery?

To exclude first and second element from jQuery, use the slice() method.

What is not() in jQuery?

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.


2 Answers

try

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

or

$("div.divToAppendTo").filter(function() { 
    return $(this).children('span.myAppendedMarkup').length == 0;  
});
like image 84
Russ Cam Avatar answered Sep 24 '22 14:09

Russ Cam


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.

like image 45
Soufiane Hassou Avatar answered Sep 26 '22 14:09

Soufiane Hassou