Introduction
jQuery is a small, battle‑tested JavaScript library that wraps common browser tasks into a compact, chainable API. It normalizes differences across browsers and lets you write fewer lines of code to select elements, react to events, animate UI changes, and communicate with servers.
At its core, jQuery provides a wrapper object around DOM elements. When you select elements with $("selector"), jQuery returns a collection that supports:
- Chaining: run multiple operations in one flow, e.g.,
$("#menu").addClass("open").slideDown() - Implicit iteration: apply the same action to every matched element without writing loops
- Consistent APIs: the same methods work across different browsers and element types
jQuery also abstracts tricky parts of DOM programming such as event handling and Ajax. For example, you can register events with simple methods (.click(), .on()) and send requests with $.ajax(), without worrying about low‑level browser differences.
$(function () {
// DOM ready shortcut
$("#saveBtn").on("click", function () {
$("#status").text("Saving...").addClass("active");
$.get("/api/status", function (data) {
$("#status").text(data.message).removeClass("active");
});
});
});
Selectors
$(document).ready(function(){
$("p").css("color","blue"); // Select all <p>
$("#idExample").hide(); // Select by id
$(".classExample").fadeIn(); // Select by class
});
jQuery selectors are CSS‑style queries that return a wrapped set of elements. They support tags, ids, classes, attributes, hierarchy, and filters. The returned set is live only at the time of selection, so re‑select if the DOM changes.
Key selector ideas:
- Specificity and performance: prefer ids and scoped selectors like
$("#form .field")over broad queries - Context selection: pass a context to limit the search area:
$(".item", "#list") - Filter selectors:
:first,:last,:visible,:not(), and attribute filters
// Attribute + filter selectors
$("input[type='email']:enabled").addClass("active");
// Context-limited selection
$(".row", "#checkout").find(".price").addClass("highlight");
Events
$(document).ready(function(){
$("#btn").click(function(){
alert("Button clicked!");
});
$(".item").hover(function(){
$(this).css("color","red");
});
});
jQuery normalizes event handling across browsers and provides both shorthand handlers and the more flexible .on() API. Prefer .on() for consistency and event delegation.
Event delegation attaches a handler to a parent and listens for events that bubble from matching children. This is essential for dynamic content.
// Delegated handler for dynamic list items
$("#list").on("click", "li", function () {
$(this).toggleClass("selected");
});
// Custom event data and namespacing
$("#panel").on("click.ui", { source: "menu" }, function (e) {
console.log(e.data.source);
});
click.ui) are easier to remove later.Effects & Animations
$("#box").hide(); // hide element
$("#box").show(); // show element
$("#box").fadeOut(1000); // fade out
$("#box").fadeIn(1000); // fade in
$("#box").slideUp(500); // slide up
$("#box").slideDown(500); // slide down
$("#box").animate({left:"100px", opacity:0.5},1000); // custom animation
jQuery effects wrap simple CSS transitions and provide built‑in easing and completion callbacks. Use them for quick UI feedback, not heavy animation.
For more control:
- Queueing: effects are queued by default on the
fxqueue - Stop/finish: interrupt animations with
.stop()or jump to end with.finish() - Custom properties: animate numeric CSS properties like
left,opacity,height
// Avoid stacked animations on repeated hover
$("#panel").hover(
function(){ $(this).stop(true, true).fadeIn(200); },
function(){ $(this).stop(true, true).fadeOut(200); }
);
DOM Manipulation
$("#para").text("New Text"); // Change text
$("#para").html("<b>Bold Text</b>"); // Change HTML
$("#list").append("<li>Item 4</li>"); // Append item
$("#list").prepend("<li>Item 0</li>"); // Prepend item
$("#div").remove(); // Remove element
jQuery provides high‑level methods for creating, updating, and removing nodes. Prefer .text() for plain text to avoid injection issues, and use .html() only with trusted content.
Efficient DOM updates:
- Batch insertions with a document fragment or build HTML once and append once
- Use
.detach()to remove elements temporarily while preserving data and events - Use
.clone(true)if you need to copy events and data
// Build once, append once const items = ["A","B","C"].map(t => `
CSS Manipulation
$("#box").css("background-color","yellow");
$("#box").addClass("highlight");
$("#box").removeClass("highlight");
$("#box").toggleClass("active");
Use class toggling for maintainable styling and keep inline styles minimal. The .css() method is useful for quick one‑off changes or dynamic values.
Advanced patterns:
- Set multiple properties at once using an object
- Toggle state classes for component behavior
- Read computed styles via
.css("property")
// Multiple properties
$("#box").css({ width: "200px", height: "120px", opacity: 0.8 });
// State-driven class toggle
$("#toggleBtn").on("click", function () {
$("#box").toggleClass("is-expanded");
});
Ajax
$.ajax({
url:"https://api.example.com/data",
method:"GET",
success:function(data){
console.log(data);
},
error:function(err){
console.error(err);
}
});
$.get("https://api.example.com/data", function(data){
console.log(data);
});
jQuery Ajax wraps XMLHttpRequest with consistent defaults and a promise‑like interface. It supports timeouts, headers, JSON parsing, and global events for logging or spinners.
Typical advanced usage includes:
- Setting headers for auth tokens
- Using
dataTypeto parse JSON automatically - Handling errors centrally with
.ajaxError()
$.ajax({
url: "/api/profile",
method: "GET",
dataType: "json",
headers: { "X-Token": "abc123" },
timeout: 5000
}).done(function (data) {
$("#name").text(data.name);
}).fail(function (xhr) {
console.error(xhr.status, xhr.responseText);
});
fetch() or a framework’s data layer.DOM Traversing
$("#list").children("li").css("color","blue"); // Select children
$("#list").parent().css("border","1px solid red"); // Select parent
$("#list").find("li:first").css("font-weight","bold"); // Find descendants
Traversing methods move around the DOM relative to your current selection. They are chainable and return new wrapped sets.
Useful traversal patterns:
.closest()to find the nearest ancestor that matches a selector.siblings()or.next()/.prev()for adjacent nodes.filter()and.not()to refine a selection
// Find the nearest card from a button click
$(".card button").on("click", function () {
$(this).closest(".card").addClass("active");
});
Utilities
$.each([1,2,3], function(index,value){
console.log(index,value);
});
$.extend(obj1,obj2); // Merge objects
$.isArray([1,2,3]); // Check if array
Utility helpers simplify common operations. They are not tied to DOM elements and can be used in any script.
Common utilities include:
$.each()for arrays or objects$.extend()for shallow merges (use carefully with nested objects)$.map()to transform arrays$.trim()and$.type()for string and type handling
const defaults = { theme: "light", size: "md" };
const options = $.extend({}, defaults, { size: "lg" });
const labels = $.map([1,2,3], n => `Item ${n}`);