Source Code: (back to article)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>closest Example</title>
</head>
<body>
<div class="outer">
<div class="inner" id="child">Click to change parent</div>
</div>
<button onclick="highlightParent()">Highlight Parent</button>
<script>
function highlightParent() {
const element = document.getElementById('child');
const parent = element.closest('.outer');
parent.style.border = '2px solid red';
}
</script>
</body>
</html>