0

Basically, I've gotten really lazy, and I've seen way too many bugs caused by typoes in really long function names, so I made a function in javascript

function getels(id){
    return document.getElementById(id);
}

Is this OK coding convention? Does it slow down the code noticeably?
Does it really matter if I use it, or should I not. It is a fairly general question, with javascript being the example I use here.

scrblnrd3
  • 7,228
  • 9
  • 33
  • 64

2 Answers2

1

You should try jQuery. However, it is fine as you are doing it. You can also do this:

var $ = function(id){
   return document.getElementById(id);
};

And then you can call

$("your_id") to get the element.

It will not slow down your script noticeably, here you can see the dummy function way is about 2% slower.

Nicolas
  • 2,297
  • 3
  • 28
  • 40
  • `getElementById` is easy to optimize: you can put all the elements with an `id` in a hash table. It does not necessarily 'take way longer than a regular function call'. – icktoofay Apr 07 '13 at 05:08
  • It does if you do not know the ids you are going to call beforehand, as it generally is the case. – Nicolas Apr 07 '13 at 05:09
  • Hash tables can look up variable keys at the same speed as constant keys. – icktoofay Apr 07 '13 at 05:11
  • 1
    No, I was referring to your claim that "`getElementById` takes way longer than a regular function call because it looks around in the DOM". Most browsers will keep a hash table themselves to look up elements by ID, and so `getElementById` is very, very fast; it does not need to traverse the DOM. There is no need to do it yourself; what you had earlier was okay. – icktoofay Apr 07 '13 at 05:19
  • I actually don't know jquery. This might be a cardinal sin on here, but I should probably learn it – scrblnrd3 Apr 07 '13 at 12:49
  • @Nicolas Hmm. The dummy function is actually about 5-7% slower on my machine – scrblnrd3 Apr 07 '13 at 12:50
0

It seems to be a fairly common practice. Specifically for getElementById. I seem to remember some google library using _gel in this way.

I see no problem with it.

A related question: Make alias to document.getElementById in Javascript

Community
  • 1
  • 1
James Montagne
  • 77,516
  • 14
  • 110
  • 130