Create an alias to document getelementbyid in JavaScript
Thursday, March 24, 2011 EDT
by: Eric Potvin
document.getElementById is pretty useful when developing Web 2.0 websites. But, writing over and over "document.getElementById" can be annoying. There is a simple way to fix that problem.
Creating an alias is a good way to simplify your code.
<script language="JavaScript" type="text/javascript">
this.$ = function(elem) {
if(typeof(elem) != "string") {
return false;
}
if(!document.getElementById(elem)) {
return false;
}
return document.getElementById(elem);
}
</script>
Now, if you want to reference a HTML tag using the ID, you simply need to use the $
$('info');
instead of:
document.getElementById('info');
Happy JavaScripting!
Last comment by: Philipp Hagemeister
Share this article: