Reputation: 335
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();
}
});
Upvotes: 0
Views: 80
Reputation: 177860
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>
Upvotes: 0
Reputation: 43481
.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>
Upvotes: 2