skip to Main Content

How do I hide a div with a nested label class using javascript? For example I have the code below and I want to hide all the div.nbd-xlabel-wrap with the nested class label.nbo-disabled-wrap.

I tried this script

function hideLabels() {
  const labels = document.querySelectorAll('.nbo-disabled-wrap');

  labels.forEach(label => {
    let currentElement = label;
    for (let i = 0; i < 5; i++) {
      if (currentElement.parentElement) {
        currentElement = currentElement.parentElement;
      } else {
        break; // Reached the top of the DOM tree
      }
    }

    const targetDiv = currentElement.querySelector('.nbd-xlabel-wrap');
    if (targetDiv) {
      targetDiv.style.display = 'none';
    }
  });
}

hideLabels();
<div class="nbd-xlabel-wrap">
  <div class="nbd-xlabel-value">
    <div class="nbd-xlabel-value-inner" title="Titanium">
      <input ng-change="check_valid();updateMapOptions('f1539147544370')" value="1" ng-model="nbd_fields['f1539147544370'].value" name="nbd-field[f1539147544370]" type="radio" id="nbd-field-f1539147544370-1" class="ng-pristine ng-untouched ng-valid ng-not-empty">
      <label class="nbd-xlabel ng-isolate-scope nbo-disabled-wrap" for="nbd-field-f1539147544370-1" nbo-disabled="!status_fields['f1539147544370'][1].enable" nbo-disabled-type="class"></label>
    </div>
  </div>
  <label for="nbd-field-f1539147544370-1"><b>Titanium</b></label>
</div>

2

Answers


  1. Instead of attempting multiple levels of parent traversal you can directly select and traverse the elements.
    Modified code-

    function hideLabels() {
      const wraps = document.querySelectorAll('.nbd-xlabel-wrap');
    
      wraps.forEach(wrap => {
        const disabledLabel = wrap.querySelector('.nbo-disabled-wrap');
        if (disabledLabel) {
          wrap.style.display = 'none';
        }
      });
    }
    
    hideLabels();
    
    Login or Signup to reply.
  2. A css only solution (as per my comment to your question) is

    .nbd-xlabel-wrap:has(.nbo-disabled-wrap) { 
        display:none; 
    }
    

    for example

    .nbd-xlabel-wrap:has(.nbo-disabled-wrap) { 
        display:none; 
    }
    <div class="nbd-xlabel-wrap">
      <div class="nbd-xlabel-value">
        <div class="nbd-xlabel-value-inner" title="Titanium">
          <input ng-change="check_valid();updateMapOptions('f1539147544370')" value="1" ng-model="nbd_fields['f1539147544370'].value" name="nbd-field[f1539147544370]" type="radio" id="nbd-field-f1539147544370-1" class="ng-pristine ng-untouched ng-valid ng-not-empty">
          <label class="nbd-xlabel ng-isolate-scope nbo-disabled-wrap" for="nbd-field-f1539147544370-1" nbo-disabled="!status_fields['f1539147544370'][1].enable" nbo-disabled-type="class"></label>
        </div>
      </div>
      <label for="nbd-field-f1539147544370-1"><b>Titanium</b></label>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search