0

I've a list of elements and each one of them have a number of types. I need to check whether this types have a certain text, if not hide the type. This should hide the types in question not the others.

The structure is:

<div class="element1">
    <dd class="event_types">
        <a>Campaigns</a>
    | 
        <a>Clubs</a>
</div>
<div class="element2">
    <dd class="event_types">
        <a>Club</a>
    | 
        <a>Other</a>
    | 
        <a>Campaigns</a>
</div>

This is what I've tried but hides all of the types if one of them is not true

var allowed = ["Sport", "Clubs", "Campaigns"];    
$('.event_types a').each(function () {
    var typeText = $(this).text();
    if  (allowed.indexOf( typeText ) > 0)  {
        $(this).hide();
    }
});
Mika
  • 305
  • 3
  • 15
  • Possible duplicate of [How do I check if an array includes an object in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) – Liam Jul 16 '19 at 11:02

2 Answers2

2

.indexOf returns -1 if element is not found, and array starts from 0:

var allowed = ["Sport", "Clubs", "Campaigns"];    
$('.event_types a').each(function () {
    var typeText = $(this).text();
    console.log(allowed.indexOf(typeText), typeText);

    if  (allowed.indexOf(typeText) == -1)  {
        $(this).hide();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element1">
    <dd class="event_types">
        <a>Campaigns</a>
    | 
        <a>Clubs</a>
</div>
<div class="element2">
    <dd class="event_types">
        <a>Club</a>
    | 
        <a>Sport</a>
    | 
        <a>Campaigns</a>
</div>
Justinas
  • 41,402
  • 5
  • 66
  • 96
0

You want to hide what is NOT in the array?

indexOf returns -1 if NOT found so that is what you need to test.

Filter is a better solution than each and I suggest a trim to make sure the text is not surrounded by whitespace

var allowed = ["Sport", "Clubs", "Campaigns"];    
$('.event_types a').filter(function () {
    var typeText = $.trim($(this).text());
    return allowed.indexOf( typeText ) === -1
}).hide();
.event_types a:before {
    content: ' | ';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element1">
    <dd class="event_types">
        <a>Campaigns</a>
        <a>Other</a>
        <a>Clubs</a>
     </dd>           
</div>
<div class="element2">
    <dd class="event_types">
        <a>Club</a>
        <a>Sport</a>
        <a>Campaigns</a>
     </dd>   
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236