How to hide DIV's parent in JS with a specific content

Issue

I’m trying to hide a DIV’s parent when a certain DIV contains a specific text.

An example. This DIV I want to stay:

<div class="report-per-day">
<div class="report-day">26 May 2022</div>
<div class="status-report-rows">
<p class="report__headline">This is our report</p>
</div>
</div>
</div>

But I want to hide this whole DIV, because there’s a DIV .mt-2, which contains "No new incident."

<div class="report-per-day">
<div class="report-day">25 May 2022</div>
<div class="mt-2" style="display: none;">
<small class="text-muted">No new incident.</small>
</div>
</div>
</div>

I have this Java Script, but it only hides the .mt-2. I’d also like to hide its 2 parents, .report-per-day and .report-day

Do you guys happen to have any suggestions? Thanks a lot!

const divs = document.getElementsByClassName('mt-2');

for (let x = 0; x < divs.length; x++) {
    const div = divs[x];
    const content = div.textContent.trim();
  
    if (content == 'No incidents reported.') {
        div.style.display = 'none';
    }
}

Solution

Loop the parent div you want to hide instead of mt-2 and check the content of mt-2 inside the loop. Try:

const divs = document.getElementsByClassName('report-per-day'); // report-per-day instead of mt-2

for (let x = 0; x < divs.length; x++) {
    const div = divs[x].querySelector('.mt-2'); // add a selector for .mt-2
    const content = div.textContent.trim();
  
    if (content == 'No incidents reported.') {
        div.style.display = 'none';
    }
}

Answered By – Enve

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.