I'm puzzled why thew second traversal with .closest seems to fail in this simple example:
function testClosest(element) {
let firstParentDiv = element.closest('div');
console.log('First Parent Div ID:', firstParentDiv.id);
let secondParentDiv = firstParentDiv.closest('div');
console.log('Second Parent Div ID:', secondParentDiv ? secondParentDiv.id : 'None');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test for .closest() Method</title>
</head>
<body>
<div id="grandparent">
Grandparent
<div id="parent">
Parent
<div id="child">
Child
<button onclick="testClosest(this)">Test Closest</button>
</div>
</div>
</div>
</body>
</html>
I'm expecting the second console log to say "parent" but instead it logs "child" again. Why is the second traversal attempt not working?
Return value
The closest ancestor Element or itself, which matches the selectors. If there are no such element, null.
MDN
You may want the .parentNode instead since it will begin with the parent element.