Solution 1 :

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.
}

Problem :

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?

Comments

Comment posted by XY problem

This really seems like an

Comment posted by u.realgeeks.media/lookinwa/js/forms.js

Here is the JS file [link[(

Comment posted by charlietfl

That doesn’t explain the higher level problem you are trying to solve with what looks like code bloat

Comment posted by charlietfl

You can probably simplify this with a common class on each of those

Comment posted by Kevin Boroumand

There is a common class, it’s “a.popup”. But when I set else if to a.popup it didn’t work.

Comment posted by link

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:

Comment posted by stackoverflow.com/questions/9899372/…

@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?

By