0

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>
Barmar
  • 741,623
  • 53
  • 500
  • 612
Stanley Tan
  • 433
  • 1
  • 7
  • 21

2 Answers2

3

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>
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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.

cjc
  • 731
  • 3
  • 13