JQuery - select children at the same level (odd or even)

Is there a way to replace the following CSS with 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
+3
source share
2 answers

Something like this might work:

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

For each .quotebody element, find the number of parent elements that have the .quotebody class, and take two modulo to determine the odd or even.

EDIT

Tested and working beautifully. This method can be a bit sluggish in complex documents, since for each jQuery element, it must go all the way back to the root element. But it works.

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

+5
source

, , while:

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");
}

, .quote-body, .quote-body, .

0

Source: https://habr.com/ru/post/1725449/


All Articles