简体   繁体   中英

If this div has this class, hide another element

I want to hide the button ONLY if a specific div (.variable-item-3) has the class "selected".

The class "selected" is added when the li is clicked.

 if($('.variable-item-3').hasClass('selected')) { $('.button').hide(); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li class="variable-item-1">Option 1</li> <li class="variable-item-2">Option 2</li> <li class="variable-item-3 selected">Option 3</li> </ul> <button type="submit" class="button">Add to cart</button> 

You need to perform the test after you change the selected class. You're just running it once when the page is loaded, it won't automatically run again when the class changes.

You can use the .toggle() function with a boolean argument to make the visibility depend on a test.

 $("li").click(function() { $("li").removeClass("selected"); $(this).addClass("selected"); $(".button").toggle(!$('.variable-item-3').hasClass('selected')); }); 
 li.selected { background-color: yellow; } .button { display: none; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li class="variable-item-1">Option 1</li> <li class="variable-item-2">Option 2</li> <li class="variable-item-3 selected">Option 3</li> </ul> <button type="submit" class="button">Add to cart</button> 

Since you are already using javascript to add the .selected class, it's probably easier to use the javascript solutions suggested in the other answers. However, if you prefer using CSS (I personally prefer using CSS to Javascript whenever possible) and if the div you care about comes before the button you care about then you can actually just use CSS.

.variable-item-3.selected ~ .button {
  display: none;
}

This assumes that .button and .selected are siblings. It gets more complicated if the two aren't siblings but it's still possible as long as an ancestor of .button is a sibling of .selected . In that case it would look something like this:

.variable-item-3.selected ~ div .button {
  display: none;
}

If the HTML isn't structured so that either of these will work, then you'll need to use one of the other solutions that does it with javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM