Disabling a button via JS if a specific element ID appears on page

I am trying to use JS to change an add to cart button to be disabled if our inventory level (displayed on the front end in a <span>) is "out of stock". This JS is already set up on our site for changing button behaviour for variants (code at the bottom of the post) and so if I can integrate an additional conditional rule using our inventory <span> that would be amazing.

Here’s the HTML for when the out of stock message appears:

<span class="LocationNoStock">Currently Sold Out</span>

I honestly have almost zero experience with JS so all I know is that I can look for elements by class name:

(document.getElementsByClassName("LocationNoStock")

Basically I want to add logic that dictates:

if class 'LocationNoStock' exists then disable 'add-to-cart' button

Any help that can be offered would be much appreciated! If it helps, our current JS for modifying the add-to-cart button is as follows – if an additional rule to search for the <span> could be inserted and mimic the behaviour that would be amazing!

updateCartButton: function(evt) {
var variant = evt.variant;
if (variant) {
if (variant.available) {
// Available, enable the submit button and change text
$(selectors.addToCart, this.$container).removeClass(classes.disabled).prop('disabled', false);
$(selectors.addToCartText, this.$container).html(theme.strings.addToCart);
} else {
// Sold out, disable the submit button and change text
$(selectors.addToCart, this.$container).addClass(classes.disabled).prop('disabled', true);
$(selectors.addToCartText, this.$container).html(theme.strings.soldOut);
}
} else {
// The variant doesn't exist, disable submit button
$(selectors.addToCart, this.$container).addClass(classes.disabled).prop('disabled', true);
$(selectors.addToCartText, this.$container).html(theme.strings.unavailable);
}
},

114 thoughts on “Disabling a button via JS if a specific element ID appears on page”