Jesse A. Green / notebook

Live demo: the DocCompiler guide library as a static, read-only snapshot (October 2026). No backend, no accounts, nothing to submit.

jQuery User Guide

Generated May 2026 from jquery/jquery at 5da206d

AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it.

1. Quick Start

jQuery is a fast, small, and feature-rich JavaScript library that simplifies HTML document traversal and manipulation, event handling, animation, and Ajax interactions. Version 4.0.0 is a modern ES module-first release under the MIT license, maintained by the OpenJS Foundation.

Key features:

  • DOM traversal and manipulation with a concise, chainable API
  • Unified event binding with delegation and namespacing
  • Animated transitions with customizable easing
  • Ajax requests with Promise-based callbacks and automatic data conversion
  • CSS manipulation including computed styles and custom properties
  • Form serialization and value management
  • Slim build available (excludes Ajax and Effects modules)

Prerequisites: A browser environment with a DOM (or Node.js with jsdom for server-side rendering).

Fastest way to start:

<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$( function() {
  $( "h1" ).css( "color", "purple" );
} );
</script>
(The page's <h1> element turns purple once the DOM is ready.)

Tip

You can also use jQuery as an ES module: import { $ } from "jquery"; in any bundler that supports the exports field in package.json.

What to try next: See Installation for all loading methods, or jump to Core Usage for DOM manipulation, events, and Ajax.

2. Installation

System Requirements

Requirement Minimum
Browser Any modern browser (Chrome, Firefox, Safari, Edge). IE is supported via compat workarounds in the source but is not a primary target for 4.x.
Node.js (optional) 18+ (for server-side usage with jsdom)
Module system ES modules (type: "module"), CommonJS, AMD, or global <script>

Installation Methods

npm

npm install jquery@4.0.0

CDN (script tag)

<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>

ES Module Import

import { $ } from "jquery";

CommonJS (Node.js)

const { $ } = require("jquery");

AMD (RequireJS)

require(["jquery"], function($) {
  // jQuery is available as $
});

Package Variants

jQuery 4.0.0 ships multiple entry points via package.json exports:

Entry Point Import Path Description
Full build "jquery" Complete library including Ajax and Effects
Slim build "jquery/slim" Excludes Ajax and Effects for smaller bundle size
Factory (full) "jquery/factory" Returns a factory function; call with a window to get a jQuery instance
Factory (slim) "jquery/factory-slim" Slim factory variant
Source modules "jquery/src/*.js" Individual source modules for advanced tree-shaking

Important

The factory builds do not attach jQuery to window automatically. You must call jQueryFactory(window) to create an instance. This is intended for server-side environments (Node.js + jsdom) where no global window exists.

Post-Install Verification

console.log( $.fn.jquery );
4.0.0

Warning

jQuery 4.0.0 requires a window with a document. If neither exists (e.g., bare Node.js without jsdom), importing jQuery directly throws: Error: jQuery requires a window with a document. Use the factory build instead.

Build from Source

git clone https://github.com/jquery/jquery.git
cd jquery
npm install
npm run build
Built files appear in dist/ and dist-module/.

The build system supports excluding modules:

npm run build -- -e deprecated       # Exclude deprecated APIs
npm run build -- -e selector         # Use native querySelectorAll only
npm run build -- --slim              # Slim build (no Ajax/Effects)

Installation Troubleshooting

Q: npm install fails with peer dependency errors.

Update npm to the latest version: npm install -g npm@latest, then retry.

Q: Script tag loads but $ is undefined.

Ensure the script tag appears before your code, and that no other library has overwritten $. Use jQuery.noConflict() to release $ back if needed.

Q: ES module import fails with "not a module" error.

Ensure your package.json includes "type": "module" or use the .mjs extension. jQuery 4.0.0 ships with "type": "module" in its own package.

3. Configuration

jQuery works out of the box with no configuration. Optional global settings control Ajax behavior, animation timing, and $ namespace conflicts.

Ajax Defaults

Customize default Ajax settings globally:

$.ajaxSetup({
  timeout: 5000,
  contentType: "application/json; charset=UTF-8",
  headers: { "X-Custom-Header": "value" }
});
Setting Default Description
url Current page URL Request URL
type "GET" HTTP method
contentType "application/x-www-form-urlencoded; charset=UTF-8" Content type for sending data
processData true Whether to convert data objects to query strings
async true Whether requests are asynchronous
cache true (except script and jsonp) Whether to cache responses
timeout 0 (no timeout) Request timeout in milliseconds
global true Whether to fire global Ajax events

Tip

Pass settings per-request to $.ajax() rather than mutating globals with $.ajaxSetup(). Global setup affects every Ajax call and can cause hard-to-debug side effects.

noConflict Mode

If another library uses $, release it:

jQuery.noConflict();
// $ is now whatever it was before jQuery loaded
// Use jQuery instead of $
jQuery( "div" ).hide();

// Or pass true to also release the jQuery variable:
var jq = jQuery.noConflict( true );
jq( "div" ).hide();

Animation Speeds

Built-in named speeds:

Name Duration (ms)
"slow" 600
"fast" 200
(default) 400

Disable all animations globally:

$.fx.off = true;

For full configuration reference including Ajax prefilters, transports, and CSS hooks, see the Admin Guide.

4. Core Usage

Selecting Elements

The $() function accepts CSS selectors, DOM elements, HTML strings, or functions:

// CSS selector
$( "div.myClass" );

// By ID
$( "#myId" );

// DOM element
$( document.body );

// HTML string → create elements
$( "<p>Hello</p>" );

// Function → document ready shortcut
$( function() {
  console.log( "DOM is ready" );
} );

Note

jQuery's selector engine uses native querySelectorAll with additional support for jQuery-specific pseudo-selectors like :hidden, :visible, :animated, and structural pseudo-classes like :nth-child.

Traversing the DOM

Navigate from a selection to related elements:

Method Description
.find( selector ) Descendants matching selector
.filter( selector ) Reduce matched set to those matching
.not( selector ) Remove elements matching selector
.is( selector ) Check if any element matches
.eq( index ) Single element at index (negative counts from end)
.first() / .last() First or last element
.even() / .odd() Even- or odd-indexed elements (0-based)
.end() Restore previous selection in chain
$( "ul" ).find( "li" ).filter( ".active" ).css( "font-weight", "bold" );

Reading and Setting Attributes

// Get attribute
$( "img" ).attr( "src" );

// Set attribute
$( "img" ).attr( "src", "photo.jpg" );

// Set multiple
$( "img" ).attr({ src: "photo.jpg", alt: "A photo" });

// Remove attribute
$( "img" ).removeAttr( "title" );

Properties vs. attributes:

// Properties (DOM state)
$( "input" ).prop( "checked" );        // true/false
$( "input" ).prop( "checked", true );

// Attributes (HTML markup)
$( "input" ).attr( "checked" );        // "checked" or undefined

Warning

Setting .attr( "value", false ) removes the attribute (except for aria-* attributes, which receive the string "false"). Use .prop() for boolean DOM properties like checked, disabled, and selected.

CSS Manipulation

// Get computed style
$( "div" ).css( "background-color" );

// Set single property
$( "div" ).css( "color", "red" );

// Set multiple properties
$( "div" ).css({ color: "red", fontSize: "16px" });

// Relative values
$( "div" ).css( "width", "+=50px" );

// Custom CSS properties
$( "div" ).css( "--my-color", "blue" );

Dimension methods:

Method Returns
.width() / .height() Content dimensions
.innerWidth() / .innerHeight() Content + padding
.outerWidth() / .outerHeight() Content + padding + border
.outerWidth( true ) / .outerHeight( true ) Content + padding + border + margin

Class Management

$( "div" ).addClass( "highlight" );
$( "div" ).removeClass( "highlight" );
$( "div" ).toggleClass( "highlight" );
$( "div" ).hasClass( "highlight" );    // true or false

// Multiple classes
$( "div" ).addClass( "foo bar baz" );

// Array syntax
$( "div" ).addClass( [ "foo", "bar" ] );

// Function callback
$( "div" ).addClass( function( index, currentClasses ) {
  return index === 0 ? "first" : "";
} );

DOM Manipulation

Inserting content:

Method Description
.append( content ) Insert at end of each element
.prepend( content ) Insert at beginning of each element
.after( content ) Insert after each element
.before( content ) Insert before each element
.appendTo( target ) Append all matched elements to target
.prependTo( target ) Prepend all matched elements to target
.html( string ) Set inner HTML
.text( string ) Set text content (HTML-escaped)

Replacing and removing:

$( "p.old" ).replaceWith( "<p>New content</p>" );
$( "p.old" ).remove();      // Removes element and its data/events
$( "p.old" ).detach();       // Removes element but preserves data/events
$( "p" ).empty();            // Removes all child nodes

Cloning:

$( "div" ).clone( true );    // true = also clone event handlers and data

Wrapping:

$( "span" ).wrap( "<div class='wrapper'></div>" );
$( "span" ).unwrap();
$( "li" ).wrapAll( "<ul class='new-list'></ul>" );
$( "p" ).wrapInner( "<strong></strong>" );

Event Handling

Binding events:

// Basic
$( "button" ).on( "click", function( event ) {
  console.log( "Clicked:", this );
} );

// With namespace
$( "button" ).on( "click.myPlugin", handler );

// Delegate (event delegation)
$( "table" ).on( "click", "td", function() {
  $( this ).toggleClass( "selected" );
} );

// One-time handler
$( "button" ).one( "click", function() {
  console.log( "This fires only once" );
} );

// Multiple events
$( "input" ).on({
  focus: function() { $( this ).addClass( "focused" ); },
  blur: function() { $( this ).removeClass( "focused" ); }
});

Removing events:

$( "button" ).off( "click" );              // All click handlers
$( "button" ).off( "click.myPlugin" );     // Namespaced only
$( "button" ).off();                       // All events

Triggering events:

$( "button" ).trigger( "click" );
$( "button" ).triggerHandler( "click" );   // No bubbling, no defaults

Note

Event namespaces (e.g., "click.myPlugin") allow plugins to bind and unbind their events without affecting other handlers. Namespaces are dot-separated and can be chained: "click.myPlugin.section1".

Document Ready

Execute code when the DOM is fully parsed:

$( function() {
  // DOM is ready
} );

// Equivalent:
$( document ).ready( function() {
  // DOM is ready
} );

jQuery's ready handler is Promise-compatible:

$.ready.then( function() {
  console.log( "DOM ready (thenable)" );
} );

Data Storage

Attach arbitrary data to DOM elements without polluting the element itself:

$( "div" ).data( "role", "container" );
$( "div" ).data( "role" );    // "container"
$( "div" ).removeData( "role" );

// HTML5 data-* attributes are auto-read on first access
// <div data-user-id="42">
$( "div" ).data( "userId" );  // 42 (auto-camelCased, auto-typed)

Warning

$.removeData() removes only jQuery-stored data. It does not remove data-* HTML attributes. After calling .removeData("key") then .data("key"), the value is re-read from the data-* attribute. (See GitHub issue #5751.)

Showing and Hiding

$( "div" ).show();
$( "div" ).hide();
$( "div" ).toggle();           // Toggle visibility
$( "div" ).toggle( true );     // Force show
$( "div" ).toggle( false );    // Force hide

Form Values

// Get value
$( "input" ).val();

// Set value
$( "input" ).val( "new value" );

// Select element
$( "select" ).val();                  // Selected value(s)
$( "select" ).val( "option2" );       // Select by value
$( "select[multiple]" ).val( [ "a", "b" ] );  // Multi-select

Serialization

$( "form" ).serialize();
// "name=John&age=30"

$( "form" ).serializeArray();
// [ { name: "name", value: "John" }, { name: "age", value: "30" } ]

// Serialize an object
$.param({ name: "John", tags: [ "a", "b" ] });
// "name=John&tags%5B%5D=a&tags%5B%5D=b"

5. Common Tasks

Load HTML Content into an Element

$( "#result" ).load( "/api/content" );

Filter the loaded content with a selector:

$( "#result" ).load( "/page.html #main-content" );

Send data with the request:

$( "#result" ).load( "/search", { query: "jquery" }, function( response, status ) {
  if ( status === "error" ) {
    $( this ).html( "Load failed." );
  }
} );

Make an Ajax GET Request

$.get( "/api/users", function( data ) {
  console.log( data );
} );

// With data type
$.getJSON( "/api/users.json", function( data ) {
  console.log( data );
} );

// Load and execute a script
$.getScript( "/plugins/myplugin.js", function() {
  console.log( "Script loaded and executed" );
} );

Make an Ajax POST Request

$.post( "/api/users", { name: "Jane", email: "[email removed]" }, function( response ) {
  console.log( "Created:", response );
} );

Full Ajax Request with Promises

$.ajax({
  url: "/api/data",
  type: "POST",
  contentType: "application/json",
  data: JSON.stringify({ key: "value" }),
  dataType: "json",
  timeout: 10000
})
.done( function( data, textStatus, jqXHR ) {
  console.log( "Success:", data );
})
.fail( function( jqXHR, textStatus, errorThrown ) {
  console.error( "Error:", textStatus, errorThrown );
})
.always( function() {
  console.log( "Request complete" );
});

Tip

The jqXHR object returned by $.ajax() implements the Promise interface. You can use .then(), .catch(), and await with it.

Animate an Element

$( "div" ).animate({
  opacity: 0.5,
  width: "50%",
  marginLeft: "+=20px"
}, {
  duration: 1000,
  easing: "swing",
  complete: function() {
    console.log( "Animation done" );
  }
});

Built-in animation shortcuts:

$( "div" ).fadeIn( 400 );
$( "div" ).fadeOut( "slow" );
$( "div" ).fadeTo( 400, 0.5 );
$( "div" ).fadeToggle();

$( "div" ).slideDown();
$( "div" ).slideUp( "fast" );
$( "div" ).slideToggle( 600 );

Chain Operations

jQuery methods return the jQuery object, enabling fluent chaining:

$( "ul.menu" )
  .find( "li" )
  .addClass( "item" )
  .filter( ".active" )
  .css( "font-weight", "bold" )
  .end()
  .find( "a" )
  .attr( "target", "_blank" );

Iterate Over Elements

$( "li" ).each( function( index, element ) {
  console.log( index, $( element ).text() );
} );

// Map to array
var texts = $( "li" ).map( function() {
  return $( this ).text();
} ).toArray();

Use Deferred Objects

var deferred = $.Deferred();

deferred.promise().then( function( value ) {
  console.log( "Resolved with:", value );
} );

deferred.resolve( "Hello" );

// Wait for multiple async operations
$.when( $.get( "/api/a" ), $.get( "/api/b" ) )
  .then( function( resultA, resultB ) {
    console.log( "Both done" );
  } );

Use the Callback List

var callbacks = $.Callbacks( "unique memory" );

callbacks.add( function( val ) {
  console.log( "A:", val );
} );

callbacks.fire( "test" );  // "A: test"

// Options: once, memory, unique, stopOnFalse

Build a jQuery Plugin

$.fn.highlight = function( color ) {
  return this.css( "background-color", color || "yellow" );
};

$( "p" ).highlight( "#ffc" );

Work with Offsets and Positions

var offset = $( "#elem" ).offset();    // { top: ..., left: ... } relative to document
var position = $( "#elem" ).position(); // { top: ..., left: ... } relative to offset parent

// Set offset
$( "#elem" ).offset({ top: 100, left: 200 });

// Scroll position
$( window ).scrollTop();
$( window ).scrollTop( 0 );

Parse HTML and XML

var nodes = $.parseHTML( "<p>Hello</p><p>World</p>" );
$( "#container" ).append( nodes );

// Parse XML
var xmlDoc = $.parseXML( "<root><item>One</item></root>" );
$( xmlDoc ).find( "item" ).text();  // "One"

6. Troubleshooting

Error: jQuery requires a window with a document

Cause: jQuery was imported in an environment without a global window object (e.g., Node.js without jsdom).

Solution:

  1. Use the factory build: import { jQueryFactory } from "jquery/factory";
  2. Create a window with jsdom: const { JSDOM } = require("jsdom"); const { window } = new JSDOM("");
  3. Pass window to the factory: const $ = jQueryFactory(window);

Prevention: Always use the factory entry point for server-side code.

Error: Syntax error, unrecognized expression: ...

Cause: An invalid CSS selector was passed to $() or .find().

Solution:

  1. Verify the selector is valid CSS
  2. Escape special characters with $.escapeSelector(): $( "#" + $.escapeSelector( myId ) )
  3. If the string looks like HTML (starts with <), jQuery will parse it as HTML instead

Prevention: Always escape dynamic values inserted into selectors.

Animation appears stuck or crashes the browser

Cause: An animation promise can enter an infinite loop under certain conditions. (See GitHub issue #5534.)

Solution:

  1. Call .stop( true, true ) on the element to clear all queued animations
  2. Check for recursive animation triggers in your code
  3. Reduce animation chaining depth

Prevention: Always .stop() active animations before starting new ones on the same element.

.offset() returns unexpected values with CSS zoom

Cause: .offset() calculations take CSS zoom into account, which may produce unexpected results in zoomed layouts. (See GitHub issue #5561.)

Solution: Manually adjust the returned values by the zoom factor, or avoid CSS zoom on offset-measured containers.

Warning

Multiple .offset()-related issues exist in jQuery 4.x. If pixel-perfect positioning is critical, verify results against getBoundingClientRect() directly.

.position() incorrect in Firefox/Chrome

Cause: .position() and .offsetParent() can return incorrect results in certain layout contexts. (See GitHub issue #3479.)

Solution: Use .offset() instead and calculate relative position manually from the parent's .offset().

focus event fires on disabled inputs

Cause: Some browsers dispatch focus events on disabled form elements, and jQuery does not suppress them. (See GitHub issue #5620.)

Solution: Guard your focus handler:

$( "input" ).on( "focus", function() {
  if ( this.disabled ) return;
  // Handle focus
} );

<script defer> fires after $(function)

Cause: Deferred scripts execute after DOMContentLoaded, which is when jQuery fires ready handlers. (See GitHub issue #3271.)

Solution: If your code depends on a deferred script, use the script's onload event instead of $(function).

JSONP requests fail silently

Cause: JSONP uses a <script> tag transport that cannot report HTTP errors or response bodies for failed requests.

Solution:

  1. Switch to CORS-enabled JSON endpoints when possible
  2. Set a timeout on the Ajax request to detect failures:
$.ajax({
  url: "https://api.example.com/data",
  dataType: "jsonp",
  timeout: 5000
}).fail( function() {
  console.error( "JSONP request timed out" );
} );

Caution

JSONP requests violate strict CSP script-src policies. Migrate to CORS-based JSON endpoints for secure environments.

.css() with vendor-prefixed properties

Cause: jQuery auto-detects vendor-prefixed CSS properties (e.g., -webkit-transform), which may produce unexpected behavior. (See GitHub issue #5585.)

Solution: Use the standard (un-prefixed) property name. jQuery resolves the correct vendor prefix internally.

await $.ajax() throws a non-Error object

Cause: When an Ajax request fails, the rejected value is a raw jqXHR object, not an Error instance. try/catch blocks may behave unexpectedly. (See GitHub issue #5668.)

Solution: Wrap the call and construct an Error explicitly:

try {
  const data = await $.ajax( "/api/data" );
} catch ( jqXHR ) {
  throw new Error( `Request failed: ${jqXHR.status} ${jqXHR.statusText}` );
}

Warning

This is a known design limitation in jQuery's Promise implementation. Future versions may change this behavior.

7. FAQ

Q: What is the difference between the full and slim builds?

The slim build (jquery/slim) excludes the Ajax module (no $.ajax, $.get, $.post, $.getJSON, $.getScript, .load()) and the Effects module (no .animate(), .fadeIn(), .slideUp(), etc.). Use slim when you handle HTTP with fetch and animations with CSS transitions.

Q: Does jQuery 4.0.0 still support Internet Explorer?

The source contains IE-specific workarounds (conditional checks via an isIE flag), but IE is not a primary support target for the 4.x branch. Behavior may degrade in IE 11 and earlier.

Q: How do I use jQuery with Content Security Policy (CSP)?

jQuery's $.globalEval() uses inline script injection, which requires script-src 'unsafe-inline' or a nonce. For strict CSP, pass a nonce via script attributes. JSONP also requires relaxed script-src. The codebase includes Trusted Types support for DOM manipulation (see GitHub issue #4963).

Q: Can I use jQuery with TypeScript?

Yes. Install type definitions: npm install @types/jquery. jQuery 4.0.0 itself does not ship built-in TypeScript declarations.

Q: How do I prevent $ conflicts with other libraries?

Call jQuery.noConflict() to release $. Pass true to also release jQuery: var jq = jQuery.noConflict(true);.

Q: What easing functions are available?

jQuery ships two built-in easing functions: linear (constant speed) and swing (sinusoidal ease-in-out, the default). For additional easing, use the jQuery UI or jQuery Easing plugin.

Q: How do I get the underlying DOM element from a jQuery object?

Use .get(0) or bracket notation [0]:

var domElement = $( "div" ).get( 0 );
var domElement = $( "div" )[ 0 ];

Q: What happened to .bind(), .unbind(), .delegate(), and .undelegate()?

These are deprecated aliases in the deprecated module. Use .on() and .off() instead. Build without deprecated methods using npm run build -- -e deprecated.

Q: How does .data() interact with data-* attributes?

On first access, .data("key") reads from the corresponding data-key HTML attribute, auto-converting JSON, numbers, and booleans. After that, the value is cached internally. Subsequent .data() calls use the cache, not the attribute. Calling .removeData() clears the cache but does not remove the HTML attribute.

Q: How do I stop all animations on an element?

$( "#elem" ).stop( true, true );  // Clear queue, jump to end

The first true clears the animation queue. The second jumps remaining animations to their final state.