0

I have a parent class .parent-class and I wanna apply some style on its only in the case if this class have a child class named as child-class. I did this way and it didn't work:

.parent-class:has(.child-class){
  background: red;  
}
claudiopb
  • 1,056
  • 1
  • 13
  • 25
  • This isn't a duplicate. It is for a child selector - not parent. There could be a way to select a child but not parent. – Aniket G Feb 26 '19 at 01:23
  • @AniketG - this _is_ a duplicate ... claudiobitar wants to select and style the _parent_ element that contains an element with the class `.child-class` -- which is exactly what the linked question is asking. The answer is - "you can't do that with just css" ... you have to use something else, like you use jquery in your (fine) answer. – Stephen P Feb 26 '19 at 01:31
  • @StephenP oh my bad. I should've read the question it was marked a duplicate for before saying that. Based off the titles, it seemed like it wasn't the same – Aniket G Feb 26 '19 at 01:35

1 Answers1

2

As far as I know, there is no way to do this using CSS.

I suggest using jQuery :has() like below.

$(".box1:has(.box2)").addClass("box3");
.box1 {
  width: 100px;
  height: 100px;
  background-color: red;
}

.box3 {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box1">
  <div class="box2"></div>
</div>

<div class="box1"></div>
Aniket G
  • 3,471
  • 1
  • 13
  • 39
  • Good answer (upvoted) but I personally don't like to mess with the styles directly like the jquery `.css(...)` does -- I prefer to find that target the same way you do, then add a class to that outer box1 :: `$('.box1:has(.box2)').addClass('outerBox')` -- now I can keep the style I want for `.outerBox` in my .css file, just like the style for `.box1` is. Doing that also allows you to restyle without having to find where in your javascript you are manipulating styles. – Stephen P Feb 26 '19 at 01:40
  • @StephenP Thanks for your advice. I'll add that into my answer – Aniket G Feb 26 '19 at 01:47