How do I check whether a variable name is "in use"? Meaning: how do I check if a variable name has already been used in a var varname = 'something'
statement?
Normally, I would just check if typeof varname == 'undefined'
, which seems to work fine. The issue is when there is an element on the page with id="varname"
. Now, when I check typeof varname == 'undefined'
, i get false
regardless, because varname
is some HTML element.
varname
is not "in use", but it is not undefined
either.
<body id="test1"></body>
<script>
//if <body> has an id of test1, how do i check if test1 is undeclared?
console.log(typeof test1 == 'undefined'); // the <body> element causes this to be true
console.log(typeof test2 == 'undefined'); // outputs true as expected
</script>
Additionally, can you check for the corner case: var test1 = document.getElementById('test1')
has been executed?
The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.
To check if a variable is undefined, you can use comparison operators — the equality operator == or strict equality operator === . If you declare a variable but not assign a value, it will return undefined automatically. Thus, if you try to display the value of such variable, the word "undefined" will be displayed.
var element = document. getElementById('elementId'); if (typeof(element) != 'undefined' && element != null) { // Exists. }
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
ifvarName
was declared and initialized (even if withnull
) and is readable from the current scope. Otherwise returnsfalse
.
DEMO jsFiddle here.
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;
}
+ ')';
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With