Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: exclude children

Tags:

jquery

I know this has been asked numerous times, and I have tried all the suggestions, and read all about varying selectors, and etc. but nothing is working for me

given the following piece of HTML:

<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's <a> tag, but nothing from the second div

I have 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.*)")

etc.

I don't know if it's because the second div has two class names, or because the second div's <a> tags are not direct children of the second div (e.g. there are font tags and such around them) but I am unable to exclude the second div.

like image 973
null Avatar asked Jul 10 '10 15:07

null


4 Answers

Have you tried the child selector > ?

div.class1 > p > a

will select only immediate descendants of class1.

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

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

Update from the comments: This works:

$(".class1 > :not(.class2.class3) a").css('border','1px solid red');
like image 122
Pekka Avatar answered Nov 14 '22 12:11

Pekka


Had the same problem, where any number of elements could be in the way, my solution was:

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

Basically, get all, then remove any that should be "excluded"

like image 41
Jonathan Regeimbal Avatar answered Nov 14 '22 11:11

Jonathan Regeimbal


Well, this depends on your exact needs, but this can work - it selects the div, the <p> directly under it, and then the link in it:

$('.class1 > p a')

To find all links except those 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);

That finds all links in your class, and remove the links that contained within another <div>, in any level. You write that a bit shorter, it you will, using:

class1.find('a[href$=jpg]').not(class1.find('div a'));
like image 2
Kobi Avatar answered Nov 14 '22 13:11

Kobi


If you use the child selector E > F rather than the descendant selector E F in combination with the element names, you will only get the desired element, e.g.:

.class1 > p > a
like image 1
Gumbo Avatar answered Nov 14 '22 12:11

Gumbo