Jquery: exclude children

I know this has been asked several times, and I tried all the suggestions and read everything about different selectors, etc., but nothing works for me

given the following HTML snippet:

<div class="class1"> <p> <a>link</a> </p> <div class="class2 class3"> <p> <font> <a>link2</a> </font> </p> </div> </div> 

I want to select the first div <a> tag, but nothing from the second div

I tried:

 $('.class1').not('.class2, .class3') $('.class1').not('.class2') $('.class1').not('.class3') $(".class1:not(.class2)") $(".class1:not(.class3)") $(".class1:not(.class2, .class3)") $("div.class1:not(.class2)") $("div.class1:not(div.class2)") $("div.class1:not(div.*)") 

and etc.

I don’t know if this is due to the fact that the second div has two class names or because the second div <a> tags are not direct children of the second div (for example, there are font tags and such around them), but I can’t exclude the second div.

+7
jquery
source share
5 answers

Have you tried the child > selector?

 div.class1 > p > a 

will select only the immediate descendants of class1 .

If you need a wider rule, I think you just need to add a space to one of your examples:

 $(".class1 :not(.class2) a") 

Update from comments: This works:

 $(".class1 > :not(.class2.class3) a").css('border','1px solid red'); 
+12
source share

If the same problem where there could be a certain number of elements, my solution would be:

 $('.class1').find("a").not(".class2 a, .class3 a").whatever; 

Basically, get everything, then delete everything that should be "excluded"

+4
source share

Well, it depends on your specific needs, but it may work - it selects a div, <p> directly below it, and then a link in it:

 $('.class1 > p a') 

To find all links except nested in another <div> , you can try something like:

 var class1 = $(".class1"); var badLinks = class1.find('div a'); // or .class2 a, .class3 a var goodLinks = class1.find('a[href$=jpg]').not(badLinks); 

This finds all the links in your class and removes the links that are contained in another <div> , at any level. You write that a little shorter is you using:

 class1.find('a[href$=jpg]').not(class1.find('div a')); 
+2
source share

If you use the child selector E > F , and not the EF descendant selector in combination with the element names, you will only get the element you need, for example:

 .class1 > p > a 
+1
source share

finally worked out an acceptable solution

 $('.class1').find('a[href$=".jpg"],a[href$=".png"],a[href$=".gif"]').each(function(){ if($(this).parents('div').attr('class') == 'class1'){do whatever}}); 

nothing worked for me. thanks for the help, although many of the answers here would work, but the first div could contain any number of children (or nothing at all) up to the second div, and the second div could contain any number of children up to the tag that I was trying to filter

0
source share

All Articles