2

Let's say our html structure looks like this:

<div class="parent">
  <div class="child"></div>
</div>

Now on some button action I add active className to child's div.

My question is:

How to style only parent element if child's div has active className

// CSS pseudo code //

if(child.has.className('active')
.parent{
background: red;
}
huhWell
  • 89
  • 1
  • 2
  • 6

2 Answers2

10

You can use the :has() pseudo class selector, although that's only supported in newer browsers. Otherwise you'll probably need to use JS.

.parent {
  background: #ccc;
}

.parent:has(.active) {
  background: steelblue;
  color: #eee;
}

/* Ignore below, for stylistic purposes only */
.parent {
  margin: 1rem;
  padding: 1rem;
  border-radius: .5rem;
  font-family: Arial, sans-serif;
}
<div class="parent">
  <div class="child">Child</div>
</div>

<div class="parent">
  <div class="child active">Child (active)</div>
</div>

For a JS-based solution there are two ways:

  • Recommended: in the code that adds the active class, you also toggle a class on the parent, say has-active-child and style it accordingly
  • Not recommended: listen to class changes on the child node using MutationObserver API and style the parent node
Terry
  • 63,248
  • 15
  • 96
  • 118
0

At the moment not all browsers support the pseudo class selector :has() as Terry explained. A JavaScript solution goes as following.

Example from GeeksForGeeks

$('ul li:has(ul.child)').addClass('has_child');
.parent > li > ul > li {
    background:orange;
}
.parent > li.has_child {
    background:red;
}
.parent li {
    background:blue;
    color:black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
    <style>
        .parent li {
            background:blue;
            color:black;
        }
        .parent > li > ul > li {
            background:orange
        }
        .parent > li > ul > li > ul >li {
            background:pink;
        }
    </style>
</head>
  
<body>
    <ul class="parent">
        <li>I am first</li>
        <li>I am second</li>
        <li>I am third</li>
        <li>I am forth</li>
        <li>I have kids.
            <ul class="child">
                <li>child1</li>
                <li>child2
                    <ul>
                        <li>child2.1</li>
                        <li>child2.2</li>
                        <li>child2.3</li>
                    </ul>
                </li>
                <li>child3</li>
                <li>child4</li>
                <li>child5</li>
            </ul>
        </li>
        <li>I am sixth</li>
        <li>I am seventh</li>
        <li>I am eight</li>
    </ul>
</body>
</html>
FUZIION
  • 1,606
  • 1
  • 6
  • 19