Search code examples
javascriptcss-selectors

Hide Div under label using JavaScript


How do I hide the div paymentProviderHeader-cc with JavaScript (not jQuery) but without the help of those classes because there is another section in the page with the same divs/classes that I don't want to hide. The only unique selector I can use in this case is the attribute for in label (for="radio-paypalcommerce").

I tried this but didn't work.

document.getElementsByClassName("label[for="radio-paypalcommerce"] > .paymentProviderHeader-cc")[0].style.visibility = "hidden";
<div class="form-field">
  <label for="radio-paypalcommerce" class="form-label optimizedCheckout-form-label">
    <div class="paymentProviderHeader-container">
      <div class="paymentProviderHeader-nameContainer" data-test="payment-method-paypalcommerce">
      </div>
      <div class="paymentProviderHeader-cc">
      </div>
    </div>
  </label>
</div>


Solution

  • You have several things wrong with your code:

    1.) You are calling document.getElementsByClassName but you are passing in a full CSS selector. That method can only be given a class name, which is why it's named that way. If you want to use a full CSS selector use document.querySelector or document.querySelectorAll instead

    2.) Your CSS selector string uses the same quotes inside the string as you use to quote the string itself. This is why you have a syntax error. See below where I use ' single quotes for the whole string and then keep the " inside for the for="..." selector.

    'label[for="radio-paypalcommerce"] > .paymentProviderHeader-cc'
    

    3.) Lastly your selector is looking for .paymentProviderHeader-cc as a direct child of the label. It's not a direct child, it's inside the .paymentProviderHeader-container element. So you can either remove the > so that it finds a child nested at any level (which is what I recommend), or you can add the extra selector in there like this

    'label[for="radio-paypalcommerce"] > .paymentProviderHeader-container > .paymentProviderHeader-cc'
    

    Here's a full working example

    document
      .querySelector('label[for="radio-paypalcommerce"] .paymentProviderHeader-cc')
      .style.visibility = "hidden";
    <div class="form-field">
      <label for="radio-paypalcommerce" class="form-label optimizedCheckout-form-label">
        <div class="paymentProviderHeader-container">
          <div class="paymentProviderHeader-nameContainer" data-test="payment-method-paypalcommerce">
          </div>
          <div class="paymentProviderHeader-cc">
          </div>
        </div>
      </label>
    </div>