Adding a Class to a Parent when Child is Hovered using JavaScript
If you have a grid of cards where each card is a hyperlink in itself (or as the immediate and only child) it is straightforward to add CSS to say, move the card up when it’s hovered.
But what if the anchor element (or any other element for that matter) is present as a nested child element in the structure and you want to add a class of hovered
on the corresponding card parent when that child element is hovered? This can be done using the following JavaScript:
document.addEventListener("DOMContentLoaded", (event) => {
const videoCardLinks = document.querySelectorAll(".video-card__link");
videoCardLinks.forEach((el) => {
el.addEventListener("mouseover", (e) => {
e.target.closest(".video-card").classList.add("hovered");
});
el.addEventListener("mouseout", (e) => {
e.target.closest(".video-card").classList.remove("hovered");
});
});
});
With the above JS, we are looping through all the .video-card__link
DOM elements and for each, attaching a couple of event listeners – one to locate the closest parent having the video-card
class and add hovered
class when the mouse is over it (incl. its child elements) and another to locate the closest parent having the video-card
class and remove hovered class when the mouse is out of it (incl. its child elements).