This is a common mistake. Instead of testing the presence of the element, you need to test the length, like so:
if ($('a[href="/blank"]').length) {...}
There are two concepts you need to be familiar with in order to understand why this works.
The first is how a jQuery wrapped set works. $('a'), for example:
When you select an element with jQuery, even if the element doesn't exist on the page, jQuery still creates the "container" (a pseudo-array) but it will be empty. This can be demonstrated by the following:
- Open the console of your browser and type in
var test = $('.doesNotExist')
- Hit enter.
- On the next line log out that variable by typing
test and hitting enter again.
You will see:
[]
This is an empty jQuery wrapped set. The set exists but is empty. You can call the .length method on this pseudo-array just as you would on a regular array, and in this case, you will get 0.
test.length // returns 0
The second concept to understand is how truthy and falsy values work in if statements:
If you put a zero (0) or a null or an empty string ("") into an if statement, the if statement will reduce it down to a false. But if you put a regular string ("hello") or a number (22) or even an empty array ([]), the if statement will evaluate it to true.
if(undefined){...} will evaluate to false
if(""){...} will evaluate to false
if(2){...} will evaluate to true
if("hiya"){...} will evaluate to true
if([]){...} will evaluate to true
As you can see, if you place an empty jQuery set ([]) into an if statement, it is considered to be a truthy value and your if block will run.
The solution is to test the length of the jQuery set, which if empty, will result in zero (0), which is a falsy value.