I often use functions like this one:
function elem(name){
return document.getElementById(name);
}
Which is used like so:
var box = elem('box');
Often, the name of the variable I'm creating is the same as the string passed to the elem function.
How can I create a function that returns an element with the same id as the variable name?
-
Do you realize you're re-inventing the wheel with that function, right ? That said there's nothing I know to do what you wish, maybe you can just drop the variable and use the function call instead ?Laurent S.– Laurent S.2015年06月22日 11:11:58 +00:00Commented Jun 22, 2015 at 11:11
4 Answers 4
The short answer is that you can't. The function has no way to know what the variable name is.
The closest you could come would be to use a horrible, horrible hack and create a global:
function box (element_id) {
window[element_id] = document.getElementById(element_id);
}
box('foo');
... but even that does the opposite of what you've asked for (creating the variable name from the string instead of the other way around).
1 Comment
function elem(name){
window[name]=document.getElementById(name);
}
Now, elem('box'); will create global variable box = document.getElementById('box'); which you can use.
Sample Code
<!DOCTYPE html>
<html>
<body>
<div id="box" onclick="hi();">box</div>
<script type='text/javascript'>
function elem(name){
window[name]=document.getElementById(name);
}
function hi(){
elem('box');
box.style.border='1px solid #ccc';
}
</script>
</body>
</html>
Comments
better make a namespace like
var ns = {};
['box', 'box2'].forEach(function (el) { ns[el] = document.getElementById(el); });
access with
ns.box.innerHtml = 'foo';
1 Comment
You can always use the DOM methods available without needing to generate a variable from the element ID. Example, instead of using
var elem = document.getElementById("box");
elem.innerHTML = "Test";
you can directly use:
box.innerHTML = "Test";
But if you really need a variable from the same name for other reasons, I think can be done is using the eval() function like so:
function box(elem){
eval("var "+ elem + " = document.getElementById('" + elem+ "');");
}