使用 JS 查找具有特定类的下一个元素
要使用JavaScript查找具有特定类的下一个元素:
- 使用 nextElementSibling 获取下一个元素兄弟。
- 在 while 循环中迭代下一个兄弟姐妹。
- 检查每个元素的类列表是否包含特定类。
以下是本文示例的 HTML。
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Box 1</div> <div class="second">Box 2</div> <div class="third">Box 3</div> <script src="index.js"></script> </body> </html>
下面是Js代码
index.js
const box = document.getElementById('box'); let third; let placeholder = box.nextElementSibling; while (placeholder) { if (placeholder.classList.contains('third')) { third = placeholder; break; } placeholder = placeholder.nextElementSibling; } console.log(third); // 👉️ div.third
我们使用了一个 while 循环来遍历 id 为 box 的元素的下一个兄弟元素。
nextElementSibling
属性返回紧随调用该方法的元素之后的元素,如果该元素是列表中的第一个元素,则返回 null。
while
循环的基本工作原理是 - 它不断迭代,直到括号之间的表达式返回一个假值或我们中断它。
JavaScript 中的假值是:null、undefined、false、0、""(空字符串)、NaN(不是数字)。
所以我们知道最终,我们要么找到类别为第三的节点,要么到达列表中的最后一个元素并跳出
while
循环。
我们使用 classList.contains
方法检查类 third 是否包含在元素的类列表中。
如果是,我们将元素分配给第三个变量并跳出 while 循环。否则,我们将占位符变量分配给下一个同级元素。
如果具有特定类的元素不存在于该元素的下一个兄弟元素中,则永远不会为第三个变量分配一个元素,并将保持设置为未定义的值。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。