What is jQuery?
jQuery is a compact, cross-browser compatible JavaScript library designed to simplify client-side scripting. It abstracts complex DOM manipulation, event handling, animation, and Ajax interactions into a concise syntax, adhering to the philosophy of "Write less, do more."
Key Advantages
- Lightweight Footprint: The core library is minimal (often under 100KB), ensuring fast page load times.
- Advanced Selectors: It offers robust CSS3-compatible selectors and custom filters, allowing developers to target DOM elements with single-line expressions rather than verbose vanilla JS loops.
- Chainable Operatinos: Methods return the jQuery object itself, allowing multiple actions to be chained in a single statement.
- CSS & Animation Support: Simplifies style manipulation and provides straightforward methods for creating dynamic visual effects.
- Simplified Ajax: Standardizes Asynchronous JavaScript and XML requests, making it easy to communicate with backend services expecting JSON or XML.
- Browser Compatibility: Handles inconsistencies between browsers (especially legacy versions) automatically.
- Extensibility: Supports a vast ecosystem of plugins for UI components like date pickers, sliders, and modal windows.
Core Concepts
The library covers the following functional areas:
- Selectors and Filters
- DOM Traversal and Manipulation
- Attribute and Property Management
- CSS Styling and Dimensions
- Event Handling
- Effects and Animations
- Utilities (
each,data) - Ajax Implementation
- Plugin Architecture
Versioning Guide
- 1.x Series: Legacy support including IE6, 7, and 8. Ideal for older enterprise environments. Final version: 1.12.4.
- 2.x Series: Dropped support for IE6-8. Smaller usage share. Final version: 2.2.4.
- 3.x Series: Modern browser focus. Removes legacy IE workarounds and supports Promises in Ajax. This is the current maintained branch, though some older plugins may not be compatible.
Note: Maintaining support for IE6-8 requires polyfills. Given the decline in usage of these browsers, many projects opt to support only modern standards.
The jQuery Object
A jQuery Object is a wrapper around a DOM element collection. It exposes jQuery-specific methods.
Example:
$('#content').html();
This retrieves the inner HTML of the element with id="content". The equivalent vanilla JavaScript is:
document.getElementById("content").innerHTML;
Important Distinction:
- jQuery objects cannot use native DOM methods (like
.innerHTML). - DOM objects cannot use jQuery methods (like
.html()).
Conversion:
var $jqueryObj = $("#element"); // jQuery Object
var domElement = $jqueryObj[0]; // Convert to DOM Object
Usage example:
$("#content").html(); // jQuery method
$("#content")[0].innerHTML; // DOM method
Syntax Fundamentals
The basic pattern is:
$(selector).action()
Locating Elements
Basic Selectors
$("#myId") // ID Selector
$("div") // Tag Selector
$(".myClass") // Class Selector
$("div.container") // Combined Selector
$("*") // Universal Selector
$("#id, .cls, div") // Multiple Selectors
Hierarchy Selectors
$("ancestor descendant") // All descendants
$("parent > child") // Direct children
$("prev + next") // Adjacent sibling
$("prev ~ siblings") // All subsequent siblings
Filtering Selectors
:first // First element
:last // Last element
:eq(index) // Element at specific index
:even // Even-indexed elements
:odd // Odd-indexed elements
:gt(n) // Index greater than n
:lt(n) // Index less than n
:not(selector) // Exclude matching elements
:has(selector) // Contains specific descendants
Example:
$("div:has(h1)") // Divs containing an h1
$("li:not(.active)") // Lis without 'active' class
Attribute Selectors
$("[href]") // Has href attribute
$("[type='email']") // Attribute equals value
$("[type!='text']") // Attribute not equal to value
Form Selectors
$(":text") // Text inputs
$(":checkbox") // Checkboxes
$(":checked") // Checked inputs/options
$(":selected") // Selected options
$(":disabled") // Disabled elements
Traversal Methods
Navigate the DOM tree relative to a selection:
Siblings and Adjacent:
$("#elem").next(); // Immediate next sibling
$("#elem").nextAll(); // All following siblings
$("#elem").prev(); // Immediate previous sibling
$("#elem").siblings(); // All siblings
Ancestry:
$("#elem").parent(); // Direct parent
$("#elem").parents(); // All ancestors
Descendants:
$("#elem").children(); // Direct children
$("#elem").find(".sub"); // Find specific descendants
Filtering:
$(".items").first();
$(".items").eq(2);
$(".items").filter(".visible");
Manipulating Elements
Class & Style
$(".box").addClass("highlight");
$(".box").removeClass("highlight");
$(".box").toggleClass("highlight");
// Inline styles
$("p").css("color", "blue");
$("p").css({"font-size": "14px", "margin": "10px"});
Dimensions & Position
$("#box").height(); // Content height
$("#box").innerHeight(); // Content + Padding
$("#box").outerHeight(); // Content + Padding + Border
$("#box").offset(); // Position relative to document
$("#box").position(); // Position relative to parent
$(window).scrollTop(); // Current scroll position
Content & Values
$("#intro").html(); // Get HTML content
$("#intro").html("<b>New</b>"); // Set HTML content
$("#nameInput").val(); // Get input value
$("#nameInput").val("John"); // Set input value
// Checkbox/Select setting
$("#multiSelect").val(["1", "3"]);
Attributes vs Properties
Use attr() for HTML attributes and prop() for DOM properties (like checked state).
$("#link").attr("href"); // Get href attribute
$("#checkBox").prop("checked", true); // Set checked property (boolean)
Difference:
attr("checked")returns the string "checked" orundefined.prop("checked")returnstrueorfalse.
DOM Modification
// Internal insertion
$("#list").append("<li>Item</li>"); // Add to end inside
$("#list").prepend("<li>Item</li>"); // Add to start inside
// External insertion
$(".target").after("<p>Next</p>"); // Add after element
$(".target").before("<p>Prev</p>"); // Add before element
// Removal
$(".unused").remove(); // Remove element completely
$(".wrapper").empty(); // Remove inner content
// Cloning
var $clone = $("#original").clone(true); // Clone with events
Event Handling
Common Events
$("#btn").click(function() { ... });
$("#input").focus(function() { ... });
$("#input").change(function() { ... });
$("#area").hover(fnIn, fnOut);
Binding and Delegation
Use .on() for attaching events, which supports event delegation for dynamically added elements.
// Direct binding
$(".static-btn").on("click", function() { ... });
// Event Delegation (for dynamic elements)
$("#table-body").on("click", ".delete-btn", function() {
$(this).closest("tr").remove();
});
Utility
// Prevent default behavior
$("#submitBtn").on("click", function(e) {
e.preventDefault();
// validation logic
});
// Stop propagation
$(".inner").on("click", function(e) {
e.stopPropagation();
});
Document Ready
Execute code only after the DOM is fully loaded.
$(document).ready(function() {
// Safe to manipulate DOM
});
// Shorthand
$(function() {
// Safe to manipulate DOM
});
Animations
jQuery provides simple methods for showing/hiding and fading elements.
$("#panel").show();
$("#panel").hide();
$("#panel").toggle();
$("#msg").fadeIn(400);
$("#msg").fadeOut(400);
$("#slider").slideDown();
$("#slider").slideUp();
// Custom animation
$(".box").animate({
opacity: 0.5,
left: "+=50"
}, 1000);
Utilities
Iteration (Each)
Iterate over jQuery collections or arrays.
// Iterating a jQuery collection
$("li").each(function(index) {
console.log(index + ": " + $(this).text());
});
// Utility for arrays
$.each(["A", "B", "C"], function(i, val) {
console.log(i, val);
});
Data Storage
Store arbitrary data associated with DOM elements.
$("#elem").data("score", 100); // Set data
var score = $("#elem").data("score"); // Get data
$("#elem").removeData("score"); // Remove data
Plugin Development
Extend jQuery's capabilities.
Static Methods ($.extend):
jQuery.extend({
customLog: function(msg) {
console.log("Plugin: " + msg);
}
});
jQuery.customLog("Hello");
Instance Methods ($.fn.extend):
jQuery.fn.extend({
makeRed: function() {
return this.css("color", "red");
}
});
$("p").makeRed();
Practical Example: Modal Dialog
<!DOCTYPE html>
<html>
<head>
<style>
.overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 999; }
.dialog { position: fixed; top: 50%; left: 50%; width: 400px; height: 300px; background: white; transform: translate(-50%, -50%); z-index: 1000; padding: 20px; }
.hidden { display: none; }
</style>
</head>
<body>
<button id="openBtn">Open Modal</button>
<div class="overlay hidden"></div>
<div class="dialog hidden">
<h2>User Info</h2>
<input type="text" id="userName" placeholder="Name">
<button id="closeBtn">Close</button>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
const $overlay = $(".overlay");
const $dialog = $(".dialog");
$("#openBtn").on("click", function() {
$overlay.add($dialog).removeClass("hidden");
});
$("#closeBtn").on("click", function() {
$overlay.add($dialog).addClass("hidden");
});
});
</script>
</body>
</html>
Practical Example: Accordion Menu
<!DOCTYPE html>
<html>
<head>
<style>
.sidebar { width: 200px; background: #333; color: white; }
.menu-header { padding: 15px; cursor: pointer; border-bottom: 1px solid #444; }
.menu-content { background: #222; display: none; }
.menu-item { padding: 10px; }
</style>
</head>
<body>
<div class="sidebar">
<div class="menu-header">Settings</div>
<div class="menu-content">
<div class="menu-item">Profile</div>
<div class="menu-item">Security</div>
</div>
<div class="menu-header">Tools</div>
<div class="menu-content">
<div class="menu-item">Calculator</div>
<div class="menu-item">Notepad</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(".menu-header").on("click", function() {
$(".menu-content").slideUp();
$(this).next(".menu-content").slideDown();
});
</script>
</body>
</html>