user20376364
user20376364

Reputation:

How to check if a particular ID does not exist then only enter into the logic

Let's say that there are 1000 of pages and each page has a unique ID. I want to apply a JavaScript code on all these pages except for one page ID (example id = 43431).

This is the code I have written(below) but for some reason the JavaScript code is still getting applied to this particular page (#43431) as well, even though I have written it so that it does not apply to this particular page.

// enter into the JS code if only this particular page ID does not exist.
if($('div').not('#43431')){
   // some JS code....
}

HTML:

<div class = "Test Home" id = "43431"> </div>

Am I missing something in my if statement?

Upvotes: 0

Views: 49

Answers (1)

Robo Robok
Robo Robok

Reputation: 22683

Your code doesn't work, because your condition always returns true, for two reasons:

  1. $('div').not('#43431') doesn't do what you think it does. Instead, it takes all divs and then narrows the collection to the ones that don't have ID equal to 43431.
  2. But that's not all. Even if previous problem didn't exist, the code still wouldn't work. Even empty jQuery collections evaluate to true:
$('#lolWhatTheHeck') == true // true

What you're looking for is checking whether a particular element exists:

if ($('#43431').length === 0) {
    // Element with ID=43431 doesn't exist
}

Upvotes: 1

Related Questions