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?
Best How To :
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>