开发者

jQuery - select children on the same level (odd or even)

开发者 https://www.devze.com 2022-12-14 07:10 出处:网络
is there a way to replace following CSS 开发者_如何学Cwith jQuery? .quote-body .quote-body { background: #f5f5f5 }

is there a way to replace following CSS 开发者_如何学Cwith jQuery?

.quote-body .quote-body { background: #f5f5f5 }
.quote-body .quote-body .quote-body { background: #fff }
.quote-body .quote-body .quote-body .quote-body { background: #f5f5f5 }
.quote-body .quote-body .quote-body .quote-body .quote-body { background: #fff }
...
and so on


Something like this might work:

$('.quote-body').each(function() {
    $(this).addClass($(this).parents('.quote-body').size() % 2 ? 'odd' : 'even');
});

For every .quotebody element, find the number of parent elements that has the class .quotebody and take modulo of two to define odd or even.

EDIT

Tested and working beautifully. This method might be a bit sluggish on complicated documents as for every element, jQuery has to traverse all the way back to the root element. But it works.

Working example: http://www.ulmanen.fi/stuff/oddevenchild.php


I can't think of a simple selector that could solve this, but you may be able to achieve the intended results using a while loop:

var $quotes = $(<containing-elem>).children(".quote-body"), level = 0;

while($quotes.length > 0) {
    $quotes.css("background-color", (level % 2 ? "#f5f5f5" : "#fff"));
    level += 1;
    $quotes = $quotes.children(".quote-body");
}

To ensure that you don't initially select too many .quote-body elements, I'm first selecting the .quote-body elements that are immediate children of the containing element.

0

精彩评论

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

关注公众号