It seems that you aren’t defining your variables in your first example. While you do declare a variable, you aren’t setting the variable.
May I suggest something of this nature?
var selected;
if (document.querySelector("a#sell")) {
selected = document.querySelector("a#sell");
} else if (document.querySelector("a#buy")) {
selected = document.querySelector("a#buy");
} else if (document.querySelector("a#area")) {
selected = document.querySelector("a#area");
} else {
selected = null;
}
Otherwise, you could also do this:
if (document.querySelector("a#sell")) {
var sell = document.querySelector("a#sell");
} else if (document.querySelector("a#buy")) {
var buy = document.querySelector("a#buy");
} else if (document.querySelector("a#area")) {
var area = document.querySelector("a#area");
} else {
var contact; // You still need to set this.
}
I am trying to define variables based on if certain Id’s exist. Example:
if (document.querySelector("a#sell")) {
var sell;
} else if (document.querySelector("a#buy")) {
var buy;
} else if (document.querySelector("a#area")) {
var area;
} else {
var contact;
}
It isn’t working. If I define them without the if/else statements below they work just fine:
var sell = document.querySelector("a#sell");
var buy = document.querySelector("a#buy");
var area = document.querySelector("a#area");
BUT I have to have the if/else statements so any contact form without those id’s would behave different. What am I doing wrong?
That doesn’t explain the higher level problem you are trying to solve with what looks like code bloat
There is a common class, it’s “a.popup”. But when I set else if to a.popup it didn’t work.
For some reason this doesn’t work. I want to note, multiple of these variables are on this page at the same time and are to be activated on click. If it helps, this is the JS file:
@KevinBoroumand The first part of my answer won’t work for your needs, but the second should be more towards that goal. Are you sure you’re not serving up those functions before the document is ready?