Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between jQuery(selector) and $(selector)?
The $ variable is an alias for jQuery. If you're using more than one JavaScript library or multiple versions of jQuery, then you should use jQuery(selector) instead of $(selector) to avoid name conflicts.
Both jQuery(selector) and $(selector) are functionally identical ? they both create jQuery objects and allow you to manipulate DOM elements. The difference lies in their usage scenarios:
$(selector) ? Short, convenient syntax used when no conflicts exist
jQuery(selector) ? Full syntax used to avoid conflicts with other libraries
Understanding noConflict() Method
The $.noConflict() method releases the $ sign to be used by other JavaScript frameworks. After calling this method, you must use the full jQuery name instead of the $ shorthand.
Example
Here's an example demonstrating the use of jQuery(selector) with noConflict() ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$.noConflict();
jQuery(document).ready(function(){
jQuery("button").click(function(){
jQuery("h3").text("jQuery works perfectly");
});
});
</script>
</head>
<body>
<h1>Testing jQuery</h1>
<h3>Click below:</h3>
<button>Click me</button>
</body>
</html>
In this example, after calling $.noConflict(), we use jQuery instead of $ for all jQuery operations. This ensures compatibility when multiple libraries are present that might also use the $ symbol.
Conclusion
Use $(selector) for simple projects with only jQuery, and jQuery(selector) when working with multiple JavaScript libraries to prevent naming conflicts.
