The jQuery selector you are using always returns a jQuery object, even if that object contains no matching elements.
So, in the if condition, you need to check that the length of the jQuery object is greater than 0, to ensure that you properly catch a failed match.
However, there is a less expensive and possibly more readable way to perform the check, and that is to test the html content of the element itself.
$(‘#linkid’).html() === ‘link1’
You can also use the this keyword in the function to refer to the clicked link, so your code could instead look like this:
I have just one question: you wrote that “The jQuery selector you are using always returns a jQuery object, even if that object contains no matching elements.” You mean :contains?
Even testing just $(‘#garbage’) when no garbage identifier exists would test as true, because $() doesn’t return an array, it returns an object.
And we all know that javascript compares objects in strange ways.
Some info about that is:
If an object is compared with a number or string, JavaScript attempts to return the default value for the object.