简体   繁体   English

当第一个初始元素没有与此jquery相当的cetrain类CSS时,请选择下一个元素

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

I have the following jQuery. 我有以下jQuery。 It loops over parent elements and then selects the first div without class active . 它循环遍历父元素,然后选择没有类active的第一个div From there, the next element is selected: 从那里,选择下一个元素:

jQuery jQuery的

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

CSS CSS

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

HTML 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. 没有jQuery我怎么能这样做。 I have a feeling there is some css4 selector to help. 我觉得有一些css4选择器可以提供帮助。 If not, a regular javascript answer will be awesome because i am trying to get away from this jquery. 如果没有,一个常规的JavaScript回答将是真棒,因为我试图摆脱这个jquery。

You could use a combination of the :first-of-type / :not() pseudo classes to select the div . 您可以使用:first-of-type / :not()伪类的组合来选择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: 既然你说你想要一个与你发布的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');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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