开发者

jQuery - select class not contained in another class [duplicate]

开发者 https://www.devze.com 2023-01-20 04:50 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: jQuery filtering selector to remove nested elements matching pattern.
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

jQuery filtering selector to remove nested elements matching pattern.

I have a hierarchy of groups. Something like:

<div class="group">
    <span class="child"></span>
    <div class="g开发者_StackOverflowroup">
        <span class="child"></span>
        <span class="child"></span>
        <span class="child"></span>
    </div>
    <span class="child"></span>
    <span class="child"></span>
    <div>This child is farther down <span class="child"></span></div>
</div>

How can I select the children in each group, without selecting any subgroup's children?

$(".group").each(function() {
    // Wrong, click fires twice (the 1st level group selects 2nd level children)
    var children = $(this).children(".child");

    // Wrong, click fires twice
    children = $(this).children(":not(.group) .child");

    // How can I properly do this??

    children.click(function() {
        alert("children.click");
    });
});

I've also tried find() instead of children() but I can't seem to get this to work correctly. Also, I can't use direct children (or >) because the descendants could be inside other non-.gorup HTML tags (i.e. several DOM levels down).


If .child is always a direct descendant of its group, then > selector will work, as noted. Otherwise, you can filter set with a function

var group = this;
$(group).find('.child').filter(function() {
    // check if current element belongs to our group
    return $(this).closest('.group')[0] == group;
})

An example


If you want only the direct children of a group you can try something like:

$('.group > .child').click(function(){
    alert('You clicked on: '+$(this).text());
});

See documentation at jQuery: child-selector

EDIT: else you might want to check out the duplicate question posted by gnarf


Try this, it is also very readable:

$(".group").each(function() {
  var allChilds = $(this).find('.child');
  var subChilds = $(this).find('.group .child');

  var firstChilds = allChilds.not(subChilds);
  firstChilds.css({ color: 'red' });
});
0

精彩评论

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