简体   繁体   中英

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

I have the following jQuery. It loops over parent elements and then selects the first div without class active . From there, the next element is selected:

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>

How could I do this without jQuery. I have a feeling there is some css4 selector to help. If not, a regular javascript answer will be awesome because i am trying to get away from this jquery.

You could use a combination of the :first-of-type / :not() pseudo classes to select the div . Then use the adjacent sibling combinator, + to select the next element:

Example Here

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

Since you said you wanted a JS equivilent to the jQuery you posted:

Example Here

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM