0

I have an array of pages

var $pages = ["events", "template", "privacy", "terms", "mentor", "party", "getinvolved", "tools"];

What I want to do is

  if ( $body[0].id !== anyOfThePageInTheArray ) {
    //do something here
    });

How can I do like if the page that they are on is not one of the page that is in the array.

I have tried .inArray and .each but I think maybe I'm doing it wrong or something.

3 Answers 3

2

The native Array.indexOf works fine:

if ($pages.indexOf($body[0].id) === -1) {
    // It's not in there
}

But if you insist on jQuery:

if ($.inArray($body[0].id, $pages) === -1) {
    // It's not in there
}
Sign up to request clarification or add additional context in comments.

2 Comments

@karthikr: OP's question had $body[0].id !== anyOfThePageInTheArray, so it looks like the condition is checking if the element isn't in the array.
it doesn't work for me I don't know why :/ It is like it never check the whole array and already returned.
2

Try:

if($pages.indexOf($body[0].id) == -1){
    //code here
}

Comments

2

You should use

if($.inArray($body[0].id,$pages) === -1)

When the second argument isn't in the array (first argument), it will return -1. Otherwise, it returns the index of the element.

By the way, $body[0].id returns e.g. "events", or is a number?

3 Comments

I think it is returning the page name for that argument
Before the if you could debug with console.log($body[0].id); console.log($pages); to know what's going wrong...
matiaslaporte I think I know what is wrong, I forgot my closing bracket on something, so this code works, but FYI your equal should be ===

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.