Reputation: 35670
I joined stackoverflow, because it's been a great help to me over the years, I'm pretty good at JavaScript, and I saw some questions I could contribute to.
I quickly found out how ubiquitous jQuery is on stackoverflow, so I decided to learn it. My first thought was, Wowzers!
I've been using my own dollar sign function, which is simply:
function $(id) {
return document.getElementById(id);
}
I know I can redefine jQuery's $ function by using noConflict()
.
However, I'd like to keep it in case noConflict()
breaks any jQuery plugins, and because I'd like my code to be easily maintainable after my upcoming retirement.
The problem is that I have tens of thousands of instances of $(...)
throughout my code.
I've come up with a method that I think will allow me to use jQuery's $ function without breaking my own code:
jQuery.noConflict();
function $(id, context) {
var r= document.getElementById(id);
return !r || context ? jQuery(id, context) : r;
}
Example at http://jsfiddle.net/0nxn3fd5/1/
I rarely use tag names as ids, and I would stop doing so altogether for any new code I write. This just seems like a quick way for me to incorporate jQuery into existing code.
Is there a problem with this approach?
Upvotes: 0
Views: 176
Reputation: 363
Why don't you just use jQuery(...) instead of $(...)? Sure, it's a little bit longer. But what else is copy pasta for?
Upvotes: 0
Reputation: 522
Given the upcoming retirement, the question is of how much you care about the developers who will take over from you. There are tools that can help you rename your old $() function. @Jason mentions find/replace, and that would most likely be sufficient. If not, there are tools like Facebook's jsgrep that may help. The repo is archived, but I shouldn't imagine that the tool should therefore stop working.
Upvotes: 0
Reputation: 4149
There are two concerns I would have using that.
You are potentially querying the DOM twice for each jQuery call. Additional, unnecessary load.
You could still have compatibility issues with jQuery dependent modules. What document.getElementById() returns is not the same as what jQuery returns (a jQuery object). So if a library used $("#element") and gets a document element back instead of a jQuery object, there likely would be an error.
I wouldn't recommend the solution. Instead, why not do a find and replace for $( prior to including jQuery?
Upvotes: 2