1

I use alot of getElementById and I have a question about what is the best way to refactor it.

As many already did, I use this code to make it simpler, easier and to reduce the file size:

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

But over to what I need help with: is it better to add a variable with the document.getElementById and just change them in every function I need it? Or, should I just stick to what I already have (the usage of $(id))

Jason Stackhouse
  • 1,558
  • 2
  • 14
  • 19
  • What does "add a variable with the document.getElementById" mean? – Quentin May 30 '12 at 16:16
  • I'm with @Quentin. I don't understand half your question. Also, I'd call your function `$id` instead of `$` so you don't have naming collisions with any of the popular libraries. – Jim Schubert May 30 '12 at 16:17
  • 3
    And "Oh no, not another wretched `$` function", there are too many of them, and [it isn't clear what any of them do](http://en.wikipedia.org/wiki/Self-documenting). If typing `document.getElementById` is that much effort, write a macro for your editor instead of a mysterious symbol that other maintainers of your code will have to interpret. – Quentin May 30 '12 at 16:17
  • If you want to reduce the file size, use something like closure compiler in your build process. – Quentin May 30 '12 at 16:22
  • @Quentin I have no idea of what you are talking about. I am not using any JavaScript Librarys. Explain to me if you want. – Jason Stackhouse May 30 '12 at 17:18
  • [The Closure Compiler is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript](https://www.google.co.uk/search?aq=f&sugexp=chrome,mod=8&sourceid=chrome&ie=UTF-8&q=closure+compiler) – Quentin May 30 '12 at 21:04
  • Thanks. I used `_` instead of `$` because it looks like C++ and has minor collison problems with others. What do you think of that? – Jason Stackhouse May 30 '12 at 21:33
  • I think it has exactly the same problem as `$`. It doesn't tell the maintainer what it does and it collides with a reasonably popular [general purpose library](http://underscorejs.org/). – Quentin May 31 '12 at 08:36
  • I am not going to use a JavaScript library, so I am guessing that is OK. – Jason Stackhouse May 31 '12 at 20:22

1 Answers1

1

Yes, window.$ = document.getElementById.bind(document); will also work. See this answer and Javascript Shorthand for getElementById in general.

If you are afraid of polluting the global namespace or conflicting with certain libraries that use the $ selector shortcut extensively (and especially their plugins), you need to make it local variable in your function's scope:

(function(/*id selector*/ $) {
    // your code here, using $
})(document.getElementById.bind(document));

is effectively the same as

(function() {
    function $(id){return document.getElementById(id);}
    // your code here, using $
})();
Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164