Hide div that contains specific text

Issue

I want to hide a div based on the text inside. In the example below I want to hide the ones with “Handtekening” and the one with “Thuis”. I prefer to do that with CSS. Is that possible?

The class names of the divs have to be the same…

<div class="test">
     Pakket
</div>
<div class="test">
     Handtekening
</div>
<div class="test">
     Thuis
</div>

If not possible with CSS, how can it be done with JavaScript?

Solution

Here’s an easy vanilla Javascript solution:

const divs = document.getElementsByClassName('test');

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

Working JSFiddle here

Remember to include the script at the end of your HTML page (right before the </body> tag).

Answered By – o01

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.