Catch the parent element in hover

6

Good Morning! Is it possible to change the parent element by hovering on 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 on <a> , I want <nav> to change 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 for js?

    
asked by anonymous 14.04.2015 / 14:06

1 answer

7

As you pointed out, the pseudo .has() pseudo selector is only 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 running before element.onmouseout , so it starts to run only after element.onmouseout .

    
14.04.2015 / 14:41