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

Time:05-26

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 >
<div >26 May 2022</div>
<div >
<p >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 >
<div >25 May 2022</div>
<div  style="display: none;">
<small >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';
    }
}

CodePudding user response:

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';
    }
}

CodePudding user response:

You can use parentElement

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 new incident.') {
        div.parentElement.style.display = 'none';
    }
}
<div >
<div >26 May 2022</div>
<div >
<p >This is our report</p>
</div>
</div>

<div >
<div >25 May 2022</div>
<div >
<small >No new incident.</small>
</div>
</div>

  • Related