jquery if div has display none addclass to parent class

14,656

Solution 1

$(".refinement_category_item:hidden").prev()
                           .children('.catresults').addClass('backgroundfilter');

Solution 2

var div = $('.refinement_category_item');

if ( ! div.is(':visible')) {
   div.parent().addClass('backgroundfilter');
}

Some notes...

  • this is set by jQuery - it is not set by an if construct.
  • Using is(':visible') is the jQuery way.
  • When adding a class with addClass(), you do not not put the leading . there.
  • It is better generally to use the DOM ready $(function() { ... }) then putting your scripts inline under the DOM elements.

Solution 3

You use $(this) where the code doesn't know what $(this) is. You should use $(".refinement_category_item") there too.

Also $(".refinement_category_item").css('display')== 'none' could also be $(".refinement_category_item").is(':hidden')

Share:
14,656
ToddN
Author by

ToddN

Updated on June 28, 2022

Comments

  • ToddN
    ToddN almost 2 years

    I want to add a class onto the div with class 'catresults' if the divs below it with class 'refinement_category_item' have a style="display:none".

     <div class="refinement_category_section">
        <div class="find_by_category_text">
          <div class="catresults">By Category</div>
        </div>
        <div class="refinement_category_item" style="display: none"> <a onclick="Add_Search_Param('cat', '2847'); Refine();" href="javascript: void(0);" class="refinement_category_link"> <span class="refinement_category_text">Back Bar Coolers (61)</span> </a> </div>
    
    
    
       $(document).ready(function(){
      if($(".refinement_category_item").not(":visible")){
      $(".refinement_category_item").parent().find("div.catresults").addClass('backgroundfilter');
      }
    });