jQuery Tutorial: Selectors, Events, DOM Methods, CSS, and Effects
jQuery is a JavaScript library for selecting HTML elements, responding to browser events, changing page content and styles, creating effects, and making Ajax requests. It provides a compact API that is still commonly encountered in existing websites, WordPress themes, plugins, and applications.
This tutorial index starts with jQuery setup and selectors, then covers DOM manipulation, attributes, CSS, dimensions, event handling, effects, traversal, and practical element checks.
How jQuery Works with JavaScript and the DOM
jQuery does not replace JavaScript. It is written in JavaScript and provides methods that simplify common browser operations. A jQuery statement normally selects one or more DOM elements and then performs an action on the matched set.
$(selector).method();
$is the commonly used jQuery function.selectoridentifies the HTML elements to match.method()reads or changes the matched elements, attaches an event handler, or applies an effect.
For example, the following statement selects every element with the class notice and hides it:
$(".notice").hide();
Install jQuery with a Download, CDN, or npm
A page must load jQuery before running code that uses $ or jQuery. You can download a production build and host it with the website, load it from a trusted CDN, or install the package in a project that uses npm.
When hosting the file locally, place the script element before code that depends on jQuery. Adjust the path to match the location used by your project.
<script src="/js/jquery.min.js"></script>
<script src="/js/app.js"></script>
For an npm-based project, install the package from the project directory:
npm install jquery
Use a single loading method unless the application has a deliberate fallback. Loading multiple copies can cause plugin conflicts, duplicate event handling, or unexpected changes to the global $ reference.
Start Writing jQuery After the DOM Is Ready
The document-ready handler waits until the browser has constructed the DOM before running code that selects page elements:
$(function () {
$("#saveButton").on("click", function () {
$("#status").text("Saved");
});
});
This example finds an element by ID, listens for its click event, and changes another element’s text. If a script is loaded with suitable deferred execution or placed after the relevant HTML, the surrounding ready handler may not always be necessary, but it remains common in existing jQuery code.
Select HTML Elements with jQuery Selectors
| Selector | Elements matched |
|---|---|
$("p") | All paragraph elements |
$(".message") | Elements with the message class |
$("#result") | The element whose ID is result |
$("ul li") | List items located inside unordered lists |
$("input[name='email']") | Input elements with the specified name attribute |
jQuery selectors are based largely on CSS selector syntax. Choose selectors that are specific enough to identify the intended elements without depending unnecessarily on a fragile page structure.
Read and Change HTML, CSS, Attributes, and Dimensions
- jQuery html()
- jQuery css()
- jQuery attr()
- jQuery empty()
- jQuery remove()
- jQuery Get Width & Height of HTML element
Many jQuery methods act as getters when called without a value and setters when a value is supplied. For example, attr("title") reads an attribute, while attr("title", "Help") sets it.
const currentTitle = $("#helpLink").attr("title");
$("#helpLink").attr("title", "Open help");
$("#status").text("Ready");
$(".card").css("border-color", "#555");
Use text() when inserting plain text. Use html() only when HTML markup is required, and do not pass untrusted input to it without appropriate sanitisation.
Set jQuery Element Content and Attributes
- jQuery – Set inner HTML of element
- jQuery – Set outer HTML of element
- jQuery – Set text content of element
Set CSS Properties with jQuery
- jQuery – Set background of element
- jQuery – Set border of element
- jQuery – Set color of element
- jQuery – Set display css property of element
- jQuery – Set font of element
- jQuery – Set font-family of element
- jQuery – Set font-size of element
- jQuery – Set font-weight of element
- jQuery – Set height of element
- jQuery – Set left css property of element
- jQuery – Set margin of element
- jQuery – Set opacity of element
- jQuery – Set overflow of element
- jQuery – Set overflow-x of element
- jQuery – Set overflow-y of element
- jQuery – Set padding of element
- jQuery – Set position css property of element
- jQuery – Set right css property of element
- jQuery – Set top css property of element
- jQuery – Set width of element
- jQuery – Set z-index of element
For reusable presentation rules, prefer adding or removing CSS classes instead of assigning many individual properties with css(). Keeping visual rules in a stylesheet makes them easier to maintain.
Handle Click, Double-Click, Hover, and Mouse Events
The on() method provides a consistent way to attach event handlers. It also supports delegated events for elements added to the page after the initial DOM was created.
$("#taskList").on("click", ".remove-task", function () {
$(this).closest("li").remove();
});
The handler is attached to #taskList, but it responds when a matching .remove-task control is clicked inside that list. This works for both existing and subsequently inserted matching elements.
Create Fade and Slide Effects with jQuery
- jQuery fadeIn()
- jQuery fadeOut()
- jQuery fadeToggle()
- jQuery slideUp()
- jQuery slideDown()
- jQuery slideToggle()
Effect methods change an element’s visibility over time. The following handler opens or closes a panel whenever its control is selected:
$("#toggleDetails").on("click", function () {
$("#details").slideToggle();
});
Do not use animation as the only way to communicate a state change. Keep controls keyboard-accessible and ensure that the interface remains understandable when users prefer reduced motion.
Traverse Parents, Children, and Sibling Elements
- jQuery – Get the parent of an element
- jQuery – Get siblings of given element
- jQuery – Get children of given element
- jQuery – Get the next sibling
- jQuery – Get the previous sibling
Traversal methods move from a selected element to related elements in the DOM. Common methods include parent(), children(), closest(), siblings(), next(), prev(), and find().
| Method | Relationship searched |
|---|---|
parent() | Immediate parent |
closest(selector) | Nearest matching element, starting with the current element and then its ancestors |
children(selector) | Direct child elements |
find(selector) | Matching descendants at any depth |
siblings(selector) | Matching elements that share the same parent |
Check Whether jQuery Elements Exist or Are Hidden
- jQuery – How to hide an element
- jQuery – How to display an element
- jQuery – How to check if element is hidden
- jQuery – How to check if element is present
- jQuery – How to display an element
A jQuery selection returns a jQuery object even when it matches no elements. Check its length property to determine whether a match exists:
const $message = $("#message");
if ($message.length > 0) {
$message.text("Element found");
}
Visibility can be checked with the :hidden or :visible selector where that behaviour matches the requirement. Remember that visibility and DOM presence are different conditions.
jQuery Ajax and jQuery UI: Related but Separate Topics
jQuery includes Ajax methods for sending HTTP requests and processing responses. Applications should handle success, validation, authentication, network failures, and server errors rather than assuming every request succeeds.
jQuery UI is a separate library built on top of jQuery. It supplies interface widgets and interactions such as dialogs, date pickers, draggable elements, and sortable lists. Loading jQuery alone does not provide jQuery UI widgets; the additional JavaScript and CSS files must be included when a project uses them.
When Learning jQuery Is Useful Today
Modern JavaScript includes native APIs for selectors, classes, events, animation, and network requests, so a new project does not automatically require jQuery. Learning jQuery remains useful when maintaining a site that already depends on it, working with older plugins, reading established front-end code, or supporting a platform where it is part of the existing stack.
For a new implementation, compare the project’s actual browser support, dependency size, existing plugins, team experience, and maintenance requirements before adding the library.
jQuery Tutorial QA Checklist
- Confirm that jQuery loads before every script that uses
$orjQuery. - Run each selector against the example HTML and verify that it matches only the intended elements.
- Check event examples with a mouse, keyboard, and dynamically added elements where delegation is used.
- Verify whether each DOM example should insert plain text with
text()or trusted markup withhtml(). - Test effect examples with hidden and visible starting states and review reduced-motion accessibility.
- Confirm that jQuery UI examples, if added, identify jQuery UI as a separate dependency.
- Test Ajax examples for successful responses, validation failures, server errors, and unavailable networks.
Frequently Asked Questions About jQuery
What is jQuery used for?
jQuery is used to select and manipulate DOM elements, handle browser events, apply effects, traverse HTML structures, and make Ajax requests through a consistent JavaScript API.
Is jQuery the same as JavaScript?
No. JavaScript is the programming language executed by the browser. jQuery is a library written in JavaScript that provides methods for common browser and DOM tasks.
Should jQuery be loaded from a CDN or hosted locally?
Both approaches can work. A CDN can simplify delivery, while local hosting gives the application direct control over availability and versioning. Consider the site’s security policy, caching strategy, privacy requirements, offline needs, and failure handling before choosing.
Is jQuery still worth learning?
It is useful for maintaining existing jQuery applications, themes, and plugins. Developers building new front-end code should also learn native JavaScript because many tasks once associated with jQuery now have widely available browser APIs.
What is the difference between jQuery and jQuery UI?
jQuery provides general DOM, event, effect, and Ajax APIs. jQuery UI is a separate library that depends on jQuery and adds interface widgets and interactions.
TutorialKart.com