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();
    }
});
1

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.