treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Apply class to parent if child div contains class

  • Is there any way that anyone knows of to pull this off:

    I have:

      <body>
          <div class="blue"></div>
      </body>
    

    What I want is to change the background of body to blue IF the div inside it has a class of blue. Same principle if it's red, green, yellow, etc.

    Does anyone know of a way to accomplish that?

  • No way in CSS. We can't target a parent with pure CSS yet.

  • Is there a way with javascript or jquery?

  • I'm doing this in a Wordpress Theme if that makes a difference...

  • No problem with jQuery. Would look something like this:

      if( $('#target').hasClass('blue') ) {
          $(document.body).addClass('yellow'); 
      }
    

    Then in your CSS you would have your styles for .blue and .yellow.

  • Yeah - I wish there was a parent selector in CSS but sadly not - Chris did an article on it - http://css-tricks.com/parent-selectors-in-css/

    Regarding your problem - TheDoc is pretty much on the money that JQuery has your back.

    I just did something for an accordion that adds a class to the parent, relevant part;

    $(this).parent().addClass("active");

    You could do something like that.

  • I have got to be doing something wrong. Here's what I have:

    In Header.php inside the head tag I put:

      <script type="text/javascript">
          if($('#ContentRow').hasClass('row Blue')){
              $(document.body).addClass('Blue');  
          }
      </script>
    

    In my page.php, I have:

      <div id="ContentRow" class="row Blue">
    
  • well - apparently I can't figure out how to do code blocks in the new forum either... one of those days - I have my if statement wrapped in script tags, and it removed them.

  • I assume you need to add '.row .blue' (make sure to use the periods!) rather than 'row blue' - that might be where the problem is coming from.

  • That didn't work either... hmmm...

  • http://codepen.io/katbella5/pen/pxutd

    No need for periods. The jQuery docs say they aren't needed.

    Make sure you are calling the jQuery library properly. I think that is likely your issue.

    -Kat

    P.S.: In other exciting news, that was my first CodePen! Yay.

  • Also, it's generally best practice to make sure you IDs and classes are lowercase. There is some preference to using camelCase out there, but I think the industry standard is lowercase with hyphens.

    So it your example:

    #ContentRow would become #content-row and .Blue would be .blue, etc.

    You don't need to add periods when using .hasClass(). It also doesn't play very nicely with multiple class names, they have to be in the proper order. So if you do .hasClass('first second') but the element on the page is actually class="second first" then hasClass() will return false.

    Here's an example for you: http://jsfiddle.net/e6kE3/

  • Having said all of that, @theacefes is probably correct - you might be trying use jQuery before the library is included. You might also want to wrap your code in something like this:

      $(document).ready(function() {
          // your code here
      });
    
  • I work for a company that uses .NET so we're all about Camel Case. I started off using underscores though.

    http://css-tricks.com/poll-results-hyphens-underscores-or-camelcase/

    It's from a while ago, but still interesting.

  • camelCase certainly has its place! I think it's all about what language you are using.

    JS/PHP - camelCase HTML/CSS - hyphens / underscores

  • Well for us it's about maintaining a consistent standard across the board I think. On a personal level, whatever makes one comfortable I think. :)

  • $(document).ready(function() {
        $('div').each(function() {
            var foo = this.className; // Get the element class...
            if ($(this).hasClass(foo)) {
                $('body').addClass(foo);
            }
        });
    });
  • I spent years working as a .NET developer, and working with other programmers that used crazy abbreviations and all lower case for their variables, and it just made it really really hard to follow the progression of their code. So I started Camel Case then and just kept going with it since to me, it made it more readable.

    @theacefes - Kudos on your first CodePen

    @Hompimpa - I finally got it working with your example and a combination of getting that code coming after the jquery call.

    @Everyone - Thank-you so much for all your help!

  • @Hompimpa - that code doesn't look quite right to me. The body is going to end up with basically all of the classes that are present on the page.

    $(this).hasClass(foo) is always going to return true.

    @ChristinaHooper - if you're looking at a specific div only, this should be what you're after:

      $(document).ready(function() {
          if( $('#target').hasClass('blue') ) {
              $(document.body).addClass('yellow'); 
          }
      });
    
  • @TheDoc: That's just an example. I guess @ChristinaHooper can understand what I mean :p

  • I think @Hompimpa 's example worked for me since I only have one div that has the class I'm searching for.

    @TheDoc Your example would be more reliable in most cases though I would think

  • This is better:

    $(document).ready(function() {
        if ($('#target').length) {
            var color = $('#target').attr('class');
            $('body').addClass(color); // or: $('#target').parent().addClass(color);
        }
    });
    <body>
        ...
        <div id="target" class="red"></div>
        ...
    <body>
  • I don't think that's better at all.

    For starters, you don't need to check #target length, that's an extra step that isn't necessary. Checking hasClass() will return true or false and will execute only if true. Since we're only checking for something specific, this is significantly more effective.

    Second, setting a variable isn't what we're looking for, since you'll be collecting all classes assigned to the #target div. What if you are looking for a classing of red but want to add a class of blue to the body?

    Third, $(document.body) should be used over $('body') based on speed alone.

    You're adding things that aren't particularly necessary to this issue, my friend!

  • ^ I second that...

  • Hi, I'm new here but I saw TheDoc's solution so I figured I should signup. I'm trying to add some colors to some CMS rendered code, and need a way to change a parent's style, when an ID is present in the child. The problem is that new class is entered on all of the matching classes not just the one with the child.

      if($('.lof-inner div').hasClass('hot')) {
     $(".lof-title").addClass("blinkurgent");
    
    } 
    
  •   <html>
      <body>  
      <div class="lof-row">  
      <div class="lof-inner" style="height:auto">
      <a class="lof-title" href=" target="_parent"> Title </a>
      <i>Thursday, 10 January 2013 14:55</i>
      <br>
      <p>
        <div class="hot">
      Some text
      <br>
      Text
      <br>
      Text
      <br>
      Some Text
        </div>
      </p>
      </div>
        </div>
    
        <div class="lof-row">  
      <div class="lof-inner" style="height:auto">
      <a class="lof-title" href=" target="_parent"> Title </a>
      <i>Thursday, 10 January 2013 14:55</i>
      <br>
      <p>
       Some text
      <br>
      Text
      <br>
      Text
      <br>
      Some Text
      </p>
      </div>
        </div>
        </body>
      </html>
    
  • eking try this: http://jsfiddle.net/SpVLK/3/

    As u see both will work:

    $('.lof-inner .hot').closest('.lof-inner').find('.lof-title').addClass('blinkurgent');
    $('.lof-inner .hot').siblings('.lof-title').addClass('bold');
    
  • Awesome! Thanks so much!

  • Okay, I apologize for my confusion I've added this to my document like this but It's not working any suggestions?

    $(document).ready(function(){
      $("body").focus(function(){
     $('.lof-inner div.hot').closest('.lof-inner').find('.lof-title').addClass('blinkurgent');
    $('.lof-inner div.hot').siblings('.lof-title').addClass('bold');
      });
    });  
    
  • Okay I got it to work in the CMS! (I had to change some settings) I'm trying to use this same method to change a background color, but it doesn't seem to work. At first I just thought that it was the CMS but I also can't get it to work in JS fiddle.

    http://jsfiddle.net/eak819/jmFe7/

    Is something incorrect?

    $('.lof-inner div.hot').siblings('.lof-row').addClass('blackred');
    

    When sibling .lof-row is found it will add .blackred then CSS takes over from there. I've also tried to use the .closest selector but no joy.

  • I fixed it, thanks guys!