Select 当第一个初始元素没有 cetrain 时的下一个元素 class CSS 等效于此 jquery

Select next element when the first initial element doesn't have a cetrain class CSS equivalent of this jquery

我有以下jQuery。它遍历父元素,然后选择第一个没有 class activediv。从那里,选择下一个元素:

jQuery

$('.parent').each(function () {
    $('div', this).eq(0).not('.active').next().addClass('selected');
});

CSS

.parent * {
    padding-left: 1em;
    display: block;
}
.main {
    border-left: 2px solid;
}
.selected {
    color: #f00;
}

HTML

<div class="parent">
    <span class="main">First Span</span>
    <span>Second Span</span>
    <div class="main">First div</div>
    <div>Second div***</div>
    <div class="main">Third div</div>
    <span>Third span</span>
</div>
<div class="parent">
    <span class="main">First Span</span>
    <span>Second Span</span>
    <div class="main active">First div</div>
    <div>Second div - dont select</div>
    <div class="main">Third div</div>
    <span>Third span</span>
</div>
<div class="parent">
    <span class="main">First Span</span>
    <span>Second Span</span>
    <div class="main">First div</div>
    <div>Second div***</div>
    <div class="main">Third div</div>
    <span>Third span</span>
</div>

如果没有 jQuery,我怎么能这样做呢?我感觉有一些 css4 选择器可以提供帮助。如果不是,一个常规的 javascript 答案会很棒,因为我正试图摆脱这个 jquery.

您可以使用 :first-of-type/:not() pseudo classes to select the div. Then use the adjacent sibling combinator, + 到 select 下一个元素的组合:

Example Here

.parent div:first-of-type:not(.active) + * {
    color: #f00;
}

既然你说你想要一个与你发布的 jQuery 等效的 JS:

Example Here

var elements = document.querySelectorAll('.parent div:first-of-type:not(.active) + *');
Array.prototype.forEach.call(elements, function (el) {
    el.classList.add('selected');
});