How to Create a New jQuery Alias with noConflict
When integrating multiple JavaScript libraries or different versions
of jQuery on the same page, naming collisions often occur over the
default $ shortcut. The jQuery.noConflict()
method solves this issue by relinquishing jQuery's control of the
$ variable. By capturing the return value of this method,
you can easily assign a custom alias to represent the jQuery object
throughout your scripts.
Assigning a Custom Shortcut
Calling jQuery.noConflict() returns a reference to the
jQuery function. To create a new alias, assign the result
of this function call to a new variable name of your choice.
// Relinquish '$' and assign jQuery to '$j'
const $j = jQuery.noConflict();
// Use the new alias
$j(document).ready(function() {
$j("button").click(function() {
$j("p").text("The new alias is working properly.");
});
});In this example, other libraries can freely use $
without conflict, while your code references jQuery using
$j.
Releasing the Global jQuery Variable
By default, noConflict() only releases the
$ symbol. If you are loading multiple versions of jQuery
and need to avoid overwriting the global jQuery object
itself, pass true as an argument to
noConflict().
// Relinquishes both '$' and 'jQuery'
const myCustomQuery = jQuery.noConflict(true);
// Use your custom variable
myCustomQuery("div").hide();Passing true ensures extreme isolation, leaving the
global namespace entirely clean of both default identifiers.
Scoping the Alias in a Closure
If you prefer to continue writing standard $ syntax
inside specific functions without polluting the global scope, you can
pass your custom alias—or the jQuery object directly—into
an Immediately Invoked Function Expression (IIFE).
const $custom = jQuery.noConflict();
(function($) {
// Inside this closure, '$' safely references jQuery
$("p").addClass("highlight");
})($custom);This pattern preserves familiar jQuery syntax locally while ensuring global compatibility across your application.