Arif YILMAZ
Arif YILMAZ

Reputation: 5866

Change color of parent div's color on a condition

I have a html code like below

<div class="class1">
    <div class="class2">
        <span class="span1"></span>

If the span with class="span1" has no value between begining and ending tags, I would like to change the color of div with class="class1"

However, span is filled with javascript after loading, so should I change the color with JS or CSS? Can anybody show me a way to do it?

I dont have any sample code to display because I am not sure how to start

Upvotes: 0

Views: 1435

Answers (4)

You can achieve this thing via jQuery using different functions css(),parents(),html().

You need to put your all code inside this $(document).ready() So this will be execute after all DOM data loaded.

For that You just need to use below code:

Html code:

<div class="class1">
    <div class="class2">
        Hello this is test message.
        <span class="span1"></span>
    </div>
  </div>  

And jquery code :

$(document).ready(function(){
        $(".span1").html().toString().length > 0 ? $(".span1").parents(".class1").css("background-color","red") : $(".class1").css("background-color","yellow");
    });

First we check the length if it's grater 0 then it will execute this

$(".span1").parents(".class1").css("background-color","red")

otherwise this:

$(".class1").css("background-color","yellow");

Here i have set background color using parents and you can directly apply via class name.

I hope this code will help you.

Upvotes: 0

Benjaco
Benjaco

Reputation: 303

You can't "go up the dom" by css, only down, so you has to do it with js. Here is som sample code:

$(function(){
   $(".span1").each(function(){
      if($(this).html() == ""){
          $(this).closest(".class1").css("background-color", "red")
      }
   })
})
span{
  height: 10px;
  display: block
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="class1">
    <div class="class2">
        <span class="span1"></span>
    </div>
</div>
<div class="class1">
    <div class="class2">
        <span class="span1">filled</span>
    </div>
</div>

Upvotes: 0

kind user
kind user

Reputation: 41893

To determine if specified element has nothing between tags, use html() function provided by jQuery. To change parent's style, use parent() and css() functions. To wait until the DOM is loaded, use ready() function.

$(document).ready(function() {
  if (!$('.span1').html()) {
    $('.span1').parent().css({ color: 'red' });
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class1">
  <div class="class2">text
    <span class="span1"></span>
  </div>
</div>

Upvotes: 1

Damien Flury
Damien Flury

Reputation: 778

document.getElementsByClassName("span1")[0].parentElement.parentElement.style.color = "green";

Upvotes: 0

Related Questions