Borislav Hadzhiev
Sun Jan 02 2022·2 min read
Photo by Looie Kang
To find the next element with specific class:
nextElementSibling
to get the next element sibling.while
loop iterate over the next siblings.Here is the HTML for the examples in this article.
<!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>
And here is the related JavaScript code.
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
We used a while
loop to iterate over the next siblings of the element with an
id
of box
.
The
nextElementSibling
property returns the element immediately following the element the method was
called on, or null
if the element is the first in the list.
while
loop basically works is - it keeps iterating until the expression between the parenthesis returns a falsy
value or we break
out of it.The falsy values in JavaScript are: null
, undefined
, false
, 0
, ""
(empty string), NaN
(not a number).
third
or we will reach the last element in the list and break out of the while
loop.We used the
classList.contains
method to check if the class third
is contained in the element's class list.
If it is, we assign the element to the third
variable and break out of the
while
loop.
Otherwise, we assign the placeholder
variable to the next sibling element.
third
variable will never get assigned an element and will remain being set to an undefined
value.