Catch the parent element in Hover

Asked

Viewed 1,874 times

6

Good Morning! Is it possible to change the parent element by giving Hover to 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 passing the mouse on <a>, I want the <nav> change the color of the border.

I’ve read something about not being able to take the parent element and that it will be available in css 4. If it’s really true, how can I do it by js?

1 answer

8


As you pointed out yourself, the pseudo selector .has() 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
}

but 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 the window.setTimeout, for the element.onmouseenter was being executed before the element.onmouseout, this way it happens to be executed only after the element.onmouseout.

  • Could illustrate better the issue of the pseudo selector .has()? Taking into account that CSS 4 has already been implemented, how it would be applied in this context?

  • 1

    updated response.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.