The only possible way to achieve what you need is through the evil eval()
, as it is not possible to access local variables through their name as strings. (Globals are possible using window["variableNameAsString"]
.)
The solution snippet presented below has the following effect:
Returns true
if varName
was declared and initialized (even if with null
) and is readable from the current scope. Otherwise returns false
.
DEMO jsFiddle here.
Source:
function removeIdOfAllElementsWithId(id) {
var element, elementsFound = [];
while ((element = document.getElementById(id)) !== null) {
element.removeAttribute('id')
elementsFound.push(element);
}
return elementsFound;
}
function assignIdToElements(elements, id) {
for (var i = 0, n = elements.length; i < n; i++) { elements[i].id = id; }
}
var isDefinedEval = '(' +
function (isDefinedEvalVarname) {
var isDefinedEvalResult;
var isDefinedEvalElementsFound = removeIdOfAllElementsWithId(isDefinedEvalVarname);
try {
isDefinedEvalResult = eval('typeof '+isDefinedEvalVarname+' !== "undefined"');
} catch (e) {
isDefinedEvalResult = false;
}
assignIdToElements(isDefinedEvalElementsFound, isDefinedEvalVarname);
return isDefinedEvalResult;
}
+ ')';
Usage:
To test if a variable with name variableName
is defined:
eval(isDefinedEval + '("' + 'variableName' + '")') === true
To check if it is not defined:
eval(isDefinedEval + '("' + 'variableName' + '")') === false
In the fiddle you'll find lots of unit tests demonstrating and verifying the behavior.
Tests:
- Several tests are included in the fiddle;
- This snippet was tested in IE7, IE8 and IE9 plus latests Chrome and Firefox.
Explanation:
The function must be used through eval()
because it needs to have access to the variables locally declared.
To access such variables, a function must be declared in the same scope. That's what eval()
does there: It declares the function in the local scope and then calls it with varName
as argument.
Aside that, the function basically:
- Removes the ID attribute of every element that has an ID === varName
;
- Checks if the variable is undefined
;
- And reassign the ID of those elements it removed the attribute.
Note: this answer was heavily edited, some coments may not be still appliable.