Question:
Good Morning! Is it possible to change the parent element by hovering the child? For example, I have the following:
nav {border:2px solid red}
nav ul li {color:#fff}
nav ul li a:hover {background-color:#ccc}
nav ul li a:hover nav {border:2px solid black}
<nav>
<ul>
<li> <a href="#">Teste</a> </li>
<li> <a href="#">Teste</a> </li>
</ul>
</nav>
When hovering over the <a>
, I want the <nav>
to change the border color.
I've read something about not being able to get the parent element and that this will be available in css 4. If it's really true, how can I do this by js?
Answer:
As you pointed out, the .has()
pseudo selector will only be available in version 4, but if it was already implemented in Browsers, you could do the following:
nav:has(> ul li a:hover) {
border:2px solid black
}
however you can achieve the desired effect by applying the following JS:
var links = document.querySelectorAll("nav ul li a");
var nav = document.querySelector("nav");
var onLinkMouseEnter = function () {
nav.classList.add("onNavHover");
}
var onLinkMouseOut = function () {
nav.classList.remove("onNavHover");
}
var onLinkMouseEnterDelay = function () {
window.setTimeout(onLinkMouseEnter, 1);
}
for (var indice in links) {
var link = links[indice];
link.onmouseenter = onLinkMouseEnterDelay;
link.onmouseout = onLinkMouseOut;
}
nav {border:2px solid red}
nav ul li {color:#fff}
nav ul li a:hover {background-color:#ccc}
.onNavHover {border:2px solid black}
<nav>
<ul>
<li> <a href="#">Teste</a> </li>
<li> <a href="#">Teste</a> </li>
</ul>
</nav>
I had to use window.setTimeout
, because element.onmouseenter
was being executed before element.onmouseout
, this way it starts to be executed only after element.onmouseout
.