0

I have multiple parent DIV elements, which has a child SPAN inside each of them. The CLASS of the SPAN changes dynamically.

I have added .parent:hover to apply certain styles to it upon hover, but I wanted NO hover effect if it's child SPAN is of a specific CLASS

Example code:

.parent {
    cursor: pointer;
}
.parent:hover {
    box-shadow: 0px 0px 9px #888888 inset;
}
.parent:hover .childActive {
    /* code that applies style to the child upon hover over the parent */
}
    /* need code that applies style to the parent upon hover, if childActive */

I can do this by a roundabout solution by adding a class dynamically to the parent whenever the child class changes to childActive

Is it possible to do this in pure css?

Prakash M.
  • 225
  • 4
  • 23
  • 5
    Unfortunately, there's not a "parent" selector in CSS, but it has been discussed in a [number](https://css-tricks.com/parent-selectors-in-css/) of [places](http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector). Other than with JS, i dont think you're going to get what you're after. If there was a parent selector you might do something like .parent:hover .childActive < .parent{ color:red; } but that would be super non-performant. Alternatively, you could apply classes to the child that "overlay" the parent's styles.. you'd have to supply your html and css to be sure though – haxxxton Feb 03 '17 at 06:54

1 Answers1

0

I definitely recommend simply adding the class to the parent instead, but here's a Javascript alternative.

With Javascript (ES5):

1: Create two functions to invoke for when the cursor hovers and leaves the "parent" div (fired in event listener).

This function adds class "active" to the "parent" div.

function parentHover(parent){
    if(parent.children[0].classList.contains('childActive')){
        parent.classList.add('active');
    }
}

This function removes class "active" from the "parent" div.

function parentLeave(parent){
  parent.classList.remove('active');
}

2: Create two event listeners for when hovering and leaving the parent div, passing through the functions created in step 1.

var parentArray = document.getElementsByClassName('active');

parentArray.forEach(function(parent){
    parent.addEventListener('mouseover', parentHover(parent));
    parent.addEventListener('mouseout', parentLeave(parent));
}

3: Add styles for class "active" when paired with class "parent"

.parent.active{
  //certain styles
}
Lex
  • 158
  • 2
  • 9