javascript - 查找某个元素后面的类

标签 javascript jquery html

我有一个具有相同类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/

相关文章:

javascript - 移动设备上性能更好的 JSON 替代方案

javascript - 使用 jquery 或 native javascript 函数编码 URL(包括 & 等字符)?

html - 如何将数据库表列表显示到 URL?

javascript - 关于更改 url 或加载 url 的 Jquery 问题

javascript - crypto.getRandomValues 会返回负值吗?

javascript - js函数与对象的比较

javascript - 将原型(prototype)代码转换为 JQuery

javascript - 扩展现有单例

javascript - 这个 javascript ajax 代码有什么问题?

javascript - 按下按钮时让烟花发射