我有一个具有相同类month
的元素列表。其中一些可能也具有类cal
,并且列表中只有一个元素具有类today
。
我想搜索 cal
类的第一个元素,但仅限于找到 today
元素之后
例如,如果我有以下列表:
<ul id="eventCal">
<li class="month"></li>
<li class="month cal">Not show because it's before TODAY</li>
<li class="month"></li>
<li class="month"></li>
<li class="month"></li>
<li class="month today">Today</li>
<li class="month"></li>
<li class="month cal">To show as it's the first CAL after the TODAY</li>
<li class="month cal">Not show because is not the first CAL</li>
<li class="month"></li>
</ul>
最佳答案
您可以使用以下选择器:
document.querySelector('.today ~ .cal') or $('.today ~ .cal').first();
这将获取第一个 .today
类之后的第一个 .cal
类。有关 ~
选择器的更多信息,请参阅 What does the “~” (tilde/squiggle/twiddle) CSS selector mean?
$('.today ~ .cal').first().css('color', 'red')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="eventCal">
<li class="month"></li>
<li class="month cal">Not show because it's before TODAY</li>
<li class="month"></li>
<li class="month"></li>
<li class="month"></li>
<li class="month today">Today</li>
<li class="month"></li>
<li class="month cal">To show as it's the first CAL after the TODAY</li>
<li class="month cal">Not show because is not the first CAL</li>
<li class="month"></li>
</ul>
关于javascript - 查找某个元素后面的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59610159/