I am trying to write a JQuery plugin to support $ in element id, my code is:
DollarSignPlugin.js:
function escapeJQueryElementName(elementName) {
elementName = elementName.replace(/\\\$/g, "$");
return elementName.replace(/\$/g, "\\$");
}
var jQueryInit = $.fn.init;
$.fn.init = function(arg1, arg2, rootjQuery){
arg2 = arg2 || window.document;
if (arg1 && arg1.replace) {
var newArg1 = escapeJQueryElementName(arg1);
return new jQueryInit(newArg1, arg2, rootjQuery);
}
return new jQueryInit(arg1, arg2, rootjQuery);
};
It is working great, but i faced one issue with current line:
var $anyselector = $("#");
JQuery throw error "Syntax error, unrecognized expression: #".
This line is from bootstrap when clicking on any tab with href="#".
This error doesn't appear when removing my plugin, also if i copy paste the replace function to directly the jquery file it works fine.
So is there a better way to override the selector or i have some issue with my code, please help?
I would strongly recommend you don't do this (but if you want to, keep reading, I do have a fix below), because:
It means you're using invalid selectors in your code, which is a maintenance issue — at some point, someone doing maintenance won't understand what's going on, or you'll hit an edge condition, etc.
Your current implementation will mess up things like
(by putting a backslash in front of the dollar sign). Who knows what else it's messing up?
Instead, I'd just have a simple:
Example:
However: If you're going to do it, you have to be careful to tread as softly as possible. That means calling the original with exactly the same number of arguments, the same
this
value, etc.; and making sure that$.fn.init.prototype
has the same value after you replace$.fn.init
as before.Doing both of those things seems to solve the problem: