Combining jQuery :not and :nth-child selectors

前端 未结 5 790
礼貌的吻别
礼貌的吻别 2021-01-19 06:56
$j(\'.select-all-these:not(.except-these):nth-child(3n)\');

I\'m trying to select every third item that doesn\'t have a particular class. This is m

5条回答
  •  渐次进展
    2021-01-19 07:34

    UPDATE: i don't think this is possible with nth-child or another selector of jQuery. so consider using a more verbose solution:

    var count = 0;
    $('.select-all-these').each(function() {
        if(!$(this).hasClass('except-these')) {
            count++;
        }
        if(count === 3) {
            $(this).text('every 3rd element');
            count = 0
        }
    });​
    

    http://jsfiddle.net/TJdFS/2/ (alternative version: http://jsfiddle.net/TJdFS/)

    :nth-child counts all matching elements ignoring any additional filters like :not.

    see jquery doc:

    The :nth-child(n) pseudo-class is easily confused with :eq(n), even though the two can result in dramatically different matched elements. With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With :eq(n) only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the (n+1)th one (n is 0-based) is selected.

    Example:

    1
    2
    3
    4
    5
    6

    JS:

    $('.select-all-these:not(.except-these):nth-child(6)').text('nth-child counts all elements (1 based!)');
    $('.select-all-these:not(.except-these):eq(1)').text('eq counts only matching elements (0 based!)');
    

    Result:

    1
    2
    3
    eq counts only matching elements. (0 based!)
    5
    nth-child counts all elements (1 based!)
    

    http://jsfiddle.net/nFtkE/2/ ​

提交回复
热议问题