0

This is my HTML:

<div class='class1'>
    <div class='class2'>
        <div class='class3'>
            <a class='link' href='alink'>Go somewhere</a>
        </div>
    </div>
<div>

What i need to do is apply a CSS class to the div that have class2, but only if they have a div with class3 inside;

.class1 .class2 ".....class3"{
    border: 1px black;
}

If class2 don't have a div inside with class3 i need to apply another CSS class:

.class1 .class2{
    border: 0;
}

Thanks.

elpidaguy
  • 475
  • 8
  • 17
MrTex
  • 151
  • 1
  • 16

4 Answers4

0

In order to select the doc with class2, you would need to find the parent of all elements with class3. Unfortunately there is no such thing as the parent selector in css. It’s been highly requested, but there are performance concerns.

Please see this answered question for more information.

Is there a CSS parent selector?

0

You will need to use JavaScript for it, Try this Jquery Code:

Add this script in your <head> tag:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Put this code in <script> tag :

   if ($(".class2 .class3").length > 0){ 
      $(".class2").css("border", "1px black")
    } else {
      $(".class2").css("border", "border: 0")
    }
elpidaguy
  • 475
  • 8
  • 17
0

Can't achieve this with CSS only. you need a bit of javascript here. In below example I'm applying .redBorder class to the .class2 div with .class3 div inside, otherwise it will have a .blackBorder class.

(function() {

  let class2Divs = document.getElementsByClassName("class2");
  
  Array.from(class2Divs).forEach(elem => {
    // check whether this div has class3 div
    if(elem.getElementsByClassName("class3").length) {
      //if this class2 div has class3 inside, run this code
      elem.classList.add("redBorder");
    }
    else {
      //if this class2 div doesn't has class3 inside, run this code
      elem.classList.add("blackBorder");
    }
  });

}());
div {
  margin: 20px;
}

.redBorder {
  border: 3px solid red;
}

.blackBorder {
  border: 3px solid black;
}
<div class="class1">
  <div class="class2">
    <div class="class3">This div has class3 div</div>
  </div>
  <div class="class2">
    <div>This div doesn't has class3 div</div>
  </div>
</div>
0

In your code the triggering point is your second div <div class="class2"> so you need to find that <div class="class2"> have any children . you can use Jquery to find this and change css

$( ".class2" ).children().css( "border", "0" );
sharun k k
  • 326
  • 3
  • 14