开发者

jquery: exclude children

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 f开发者_JAVA技巧ollowing 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.


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');


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"


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'));


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


well, 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 else was working for me. thanks for the help though, many of the answers here would have worked but the first div could contain any number of child elements (or none at all) before the second div, and the second div could contain any number of child elements before the a tag that i was trying to filter out

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜