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
Instead of attempting multiple levels of parent traversal you can directly select and traverse the elements.
Modified code-
A css only solution (as per my comment to your question) is
for example