Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide div that contains specific text

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?

like image 808
Jilco Tigchelaar Avatar asked Oct 17 '17 13:10

Jilco Tigchelaar


People also ask

How do I hide certain elements in HTML?

To hide an element, set the style display property to “none”. document. getElementById("element").

How do I hide an element in Dom?

Completely hiding elements can be done in 3 ways: via the CSS property display , e.g. display: none; via the CSS property visibility , e.g. visibility: hidden; via the HTML5 attribute hidden , e.g. <span hidden>


2 Answers

Here's an easy vanilla Javascript solution:

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

for (let x = 0; x < divs.length; x++) {
    let div = divs[x];
    let content = div.innerHTML.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).

like image 135
o01 Avatar answered Sep 19 '22 11:09

o01


If you have control over the HTML output and have no problems with the text document getting twice as big, you can duplicate the content of each of those divs. Otherwise JavaScript is the way to go. Here is the CSS solution:

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

Then use the selector for an attribute containing a string:

div[content~=Thuis] { display:none; }

The one above will match when "Thuis" is contained in the text as a separate word. If you want to match any occurrence of the string, you should use:

div[content*=and] { display:none; }
like image 27
DreamWave Avatar answered Sep 20 '22 11:09

DreamWave