用javascript隐藏父div

问题描述 投票:0回答:1

如何使用 javascript 隐藏带有嵌套标签类的 div?例如,我有下面的代码,我想隐藏所有带有嵌套类 label.nbo-disabled-wrap 的 div.nbd-xlabel-wrap 。

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

我尝试了这个脚本。

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();
javascript hide divider
1个回答
0
投票

您可以直接选择并遍历元素,而不是尝试多级父级遍历。 修改后的代码-

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();
© www.soinside.com 2019 - 2024. All rights reserved.