Hide Div under label

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”).

<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>

I tried this but didn’t work.

document.getElementsByClassName("label[for="radio-paypalcommerce"] > .paymentProviderHeader-cc")[0].style.visibility = "hidden";

Can you try

document.querySelector('[for=radio-paypalcommerce] .paymentProviderHeader-cc').hidden = true;

You can always use the template string back-ticks.

const paymentProvider = document.querySelector(
  `label[for="radio-paypalcommerce"] .paymentProviderHeader-cc`
)

paymentProvider.hidden = true

One thing I did notice — The hidden attribute is overridden by the display property, so if that element has a display set to ‘block’, the hidden attribute will not work. Maybe something to bear in mind.

That’s why I prefer to add a class with

Display=‘none’

To hide an element

1 Like

Just to elaborate.

CSS

.hidden {
  display: none;
}

JS

const paymentProvider = document.querySelector(
  `label[for="radio-paypalcommerce"] .paymentProviderHeader-cc`
)

paymentProvider.classList.add('hidden')

Maybe I am missing something, but on that basis why the need for JS? Why not just set the style in CSS?

label[for="radio-paypalcommerce"] .paymentProviderHeader-cc {
  display: none;
}

Off-topic: it would be remiss of me not to say that a label element can’t have divs as children. Block elements are not permitted as children of a label element and they need to be phrasing elements like spans to be valid.

They will do no harm in reality but of course will not validate.

1 Like

The label is redundant as you should not use the for attribute for other elements then labels or do I miss something?

Yes you are probably right, but it does spell out what it is. I would say for the extra few letters/specificity it is quicker and easier to grasp what the element in the selector is.

1 Like

Thanks guys for the detailed answers, I found the correct code:

document.querySelector('label[for="radio-paypalcommerce"] .paymentProviderHeader-cc').style.visibility = "hidden";

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.