Login Or Sign up

changing the text color of the child class of a sibling of another class

196 Views Asked by At

How to create that conditional check to perform a certain action? Ex:

<h1 class = "parentclass1">
     <p class = "childclass1"></p> <!--- This child class is conditional--->
</h1>
<h1 class = "parentclass2">
     <p class = "childclass2"></p>
</h1>

I want to change the text color of "childclass2" only if the "parentclass1" has "childclass1, otherwise, ignore it. (The following code has id name instead of class for the parent class name)

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
  if($("h5").parent().find("hide")){
    #price-field .money {color:red};
  }
</script>
</head>
<body>
<h5 class="compare-at-price js" style="font-size: 14px;">
    <span class="money" style="font-size: 14px;">$60</span>
    </h5>
<h3 class="custom-font" id="price-field" style="font-size: 24px;">
    <span class="money" style="font-size: 24px;">$50</span>
    </h3>
<h5 class="compare-at-price js hide" style="font-size: 14px;">
    </h5>
 <h3 class="custom-font" id="price-field" style="font-size: 24px;">
    <span class="money" style="font-size: 24px;">$70</span>
    </h3>
</body>

</html>
1

There are 1 best solutions below

2
sid On

use hasClass function on the child element.

if($(".parentclass1").children("p").hasClass("childclass1")) {
   $(".childclass2").css('color', 'red');
}

Ref: https://api.jquery.com/hasclass/