Skip to main content

Welcome to Ahex Technologies

jQuery Basics

Jquery Basics
  • August 19, 2026
  • Sanjay
  • 0

jQuery has been around since 2006, and it still runs on roughly three out of four websites that use any JavaScript library at all. If you have inherited a WordPress theme, a legacy admin panel, or a business application built five years ago, you will meet jQuery whether you planned to or not.

This guide covers the jQuery basics you actually need β€” selectors, DOM manipulation, events, effects and Ajax β€” with working examples for each. It also answers the question most developers are really asking in 2026: is jQuery still worth using, and if not, what should replace it?

We have written this so a beginner can follow it end to end, and so a team lead deciding what to do with an old codebase gets a straight answer.


What jQuery actually does

jQuery is a JavaScript library with one core purpose: making it shorter and safer to find elements on a page and do things to them.

When jQuery was released, browsers disagreed with each other constantly. Internet Explorer used one method for attaching events, Firefox used another. Selecting an element by class required writing a loop by hand. jQuery smoothed all of that over behind a single function β€” $() β€” and gave developers one API that worked everywhere.

Here is the difference it made at the time:

javascript

// Plain JavaScript, circa 2008
var elements = document.getElementsByClassName('alert');
for (var i = 0; i < elements.length; i++) {
  elements[i].style.display = 'none';
}

// jQuery
$('.alert').hide();

That gap in verbosity is why jQuery took over. Much of the gap has since closed, which we cover further down β€” but understanding what jQuery was solving makes the rest of the library make sense.


Adding jQuery to a page

There are three ways to include it, and the right one depends on your project.

CDN β€” fastest to start with

html

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

Local file β€” when you need offline builds or full control

html

<script src="/js/jquery-3.7.1.min.js"></script>

npm β€” for build-tool projects

bash

npm install jquery

javascript

import $ from 'jquery';

Two things to watch. First, always place the script tag before any code that uses $, or the browser will throw $ is not defined. Second, if you are working inside WordPress, jQuery is already loaded and runs in no-conflict mode β€” you need jQuery instead of $, or you need to wrap your code as shown below.

javascript

jQuery(document).ready(function($) {
  // $ works safely inside here
});

If you are unsure which version a live site is running, open the console and type jQuery.fn.jquery.


Document ready: run code at the right time

Your JavaScript will fail if it runs before the HTML it targets exists. jQuery gives you a wrapper that waits for the DOM to be parsed.

javascript

$(document).ready(function() {
  console.log('DOM is ready');
});

// Shorthand β€” identical behaviour
$(function() {
  console.log('DOM is ready');
});

This is different from window.onload, which waits for images and stylesheets as well. ready fires earlier, which is usually what you want.

The modern equivalent without jQuery:

javascript

document.addEventListener('DOMContentLoaded', function() {
  console.log('DOM is ready');
});

jQuery selectors

Selectors are the heart of the library. If you know CSS selectors, you already know most of this.

javascript

$('#header')            // by ID
$('.card')              // by class
$('p')                  // by tag
$('input[type="email"]') // by attribute
$('ul li:first')        // first list item
$('tr:even')            // alternate table rows
$('.card:visible')      // only visible elements
$('a:contains("Download")') // by text content

Traversal β€” moving around the DOM once you have a starting point:

javascript

$('.card').find('.title')    // descendants
$('.card').parent()          // direct parent
$('.card').closest('section') // nearest matching ancestor
$('.card').siblings()        // all siblings
$('.card').next()            // next sibling
$('.card').eq(2)             // third match, zero-indexed

The performance point most tutorials skip: every call to $() searches the document. If you use the same selector three times, you have searched three times. Cache it in a variable instead.

javascript

// Wasteful
$('.sidebar').addClass('open');
$('.sidebar').css('width', '300px');
$('.sidebar').fadeIn();

// Better β€” one lookup
var $sidebar = $('.sidebar');
$sidebar.addClass('open');
$sidebar.css('width', '300px');
$sidebar.fadeIn();

Prefixing cached jQuery objects with $ is a widely used convention that makes code far easier to read. Small habits like this matter more than they look β€” we cover a few more in our guide to performance-oriented front-end development.


DOM manipulation

Once you have selected something, these are the methods you will reach for daily.

Reading and writing content

javascript

$('#title').text();              // get text
$('#title').text('New heading'); // set text
$('#body').html('<b>Bold</b>');  // set HTML
$('#email').val();               // get form value
$('#email').val('a@b.com');      // set form value

Use text() rather than html() whenever you are inserting content that came from a user or an API. html() will execute any script tags in that string, which is a cross-site scripting hole.

Attributes and properties

javascript

$('img').attr('src', '/new.jpg');
$('#terms').prop('checked', true);   // for checked, disabled, selected
$('#row').data('user-id');           // reads data-user-id
$('a').removeAttr('target');

attr() and prop() catch people out. Use prop() for boolean states such as checked and disabled; use attr() for everything else.

Classes and styles

javascript

$('.card').addClass('active');
$('.card').removeClass('active');
$('.card').toggleClass('active');
$('.card').hasClass('active');    // returns true or false
$('.card').css('color', '#4f46e5');
$('.card').css({ color: '#4f46e5', padding: '20px' });

Prefer adding and removing classes over setting inline styles. It keeps your presentation in the stylesheet where it belongs, and it is far easier to maintain β€” the same principle behind working with a CSS framework rather than hand-writing styles everywhere.

Adding and removing elements

javascript

$('#list').append('<li>Last</li>');   // inside, at the end
$('#list').prepend('<li>First</li>'); // inside, at the start
$('#list').after('<p>After</p>');     // outside, following
$('#list').before('<p>Before</p>');   // outside, preceding
$('#list li').remove();               // delete elements
$('#list').empty();                   // delete children, keep the element

Event handling

Events are how your page responds to people.

javascript

$('#submit').on('click', function() {
  console.log('Clicked');
});

$('#email').on('input', function() {
  console.log($(this).val());
});

$('#form').on('submit', function(e) {
  e.preventDefault();   // stop the page reloading
  // validate and send
});

$(this) inside a handler refers to the element that fired the event, wrapped as a jQuery object.

Event delegation β€” the concept worth understanding properly

If you attach a handler to elements that exist now, and then add more of those elements later, the new ones will not respond. Delegation solves this by attaching the handler to a stable parent and filtering by selector when the event bubbles up.

javascript

// Breaks for rows added after this line runs
$('.delete-btn').on('click', handleDelete);

// Works for every row, including future ones
$('#table').on('click', '.delete-btn', handleDelete);

This one pattern accounts for a large share of the “my button stopped working” bugs in jQuery codebases. It matters most in anything that renders rows dynamically β€” tables, search results, cart items.

Removing handlers

javascript

$('#submit').off('click');
$('#modal').one('click', openOnce);  // fires a single time, then unbinds

Effects and animation

javascript

$('.panel').hide();
$('.panel').show();
$('.panel').toggle();
$('.panel').fadeIn(400);
$('.panel').fadeOut(400);
$('.panel').slideDown(300);
$('.panel').slideUp(300);

$('.panel').animate({ opacity: 0.5, left: '250px' }, 500);

A callback runs when the animation finishes:

javascript

$('.panel').fadeOut(300, function() {
  $(this).remove();
});

Worth knowing: jQuery animates using JavaScript timers, while CSS transitions and @keyframes are handled by the browser’s compositor and can be hardware-accelerated. For anything visual and repeated β€” hover states, menu slides, loading spinners β€” CSS will be smoother. Keep jQuery animation for cases where the values are genuinely dynamic.


Ajax with jQuery

Ajax is what made jQuery indispensable for a decade β€” loading data without reloading the page.

javascript

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

$.post('/api/users', { name: 'Priya', role: 'admin' }, function(response) {
  console.log(response);
});

The full form gives you proper control:

javascript

$.ajax({
  url: '/api/users',
  method: 'POST',
  contentType: 'application/json',
  data: JSON.stringify({ name: 'Priya' }),
  success: function(response) {
    $('#result').text('Saved');
  },
  error: function(xhr, status, error) {
    $('#result').text('Something went wrong: ' + error);
  }
});

Loading a fragment of HTML straight into a container:

javascript

$('#panel').load('/partials/user-card.html');

Almost every API you talk to will return JSON, so it is worth being comfortable with the format itself β€” our introduction to JSON covers the structure and the common parsing mistakes. If you are designing the API on the other side of these calls, the tradeoffs between protocols are covered in gRPC vs REST.


Chaining

Most jQuery methods return the same jQuery object, so calls can be strung together.

javascript

$('#alert')
  .addClass('visible')
  .css('background', '#fef3c7')
  .text('Saved successfully')
  .fadeIn(300)
  .delay(2000)
  .fadeOut(300);

Readable and efficient, because the selector runs once. Break long chains across lines as above rather than running them together.


Five mistakes beginners make

  1. Not caching selectors. Calling $('.item') in a loop searches the whole document on every iteration.
  2. Using html() for user input. This is an XSS vulnerability. Use text().
  3. Forgetting e.preventDefault() on form submits. The page reloads and your Ajax call never completes.
  4. Attaching handlers directly to dynamic content. Use delegation.
  5. Loading jQuery twice. A theme includes one version, a plugin includes another, and behaviour becomes unpredictable. Check with jQuery.fn.jquery before adding anything.

jQuery vs vanilla JavaScript

The reason jQuery existed has largely gone away. Modern browsers now provide equivalents for nearly everything it made easy.

TaskjQueryVanilla JavaScript
Select one element$('#id')document.querySelector('#id')
Select many$('.cls')document.querySelectorAll('.cls')
Add a class$el.addClass('x')el.classList.add('x')
Set text$el.text('hi')el.textContent = 'hi'
Attach an event$el.on('click', fn)el.addEventListener('click', fn)
Ajax request$.ajax({...})fetch(url).then(r => r.json())
Hide an element$el.hide()el.style.display = 'none'
Wait for DOM$(fn)document.addEventListener('DOMContentLoaded', fn)

The vanilla versions are slightly longer to type. They also ship zero kilobytes to the browser. jQuery 3.7 minified and gzipped is roughly 30KB β€” not enormous, but it is 30KB of parse and execute time on every page load, for functionality the browser already has.


Is jQuery still worth using in 2026?

Here is a straight answer rather than a hedge.

SituationRecommendation
Maintaining an existing jQuery codebaseKeep it. Rewriting working code for its own sake is a poor use of budget.
WordPress theme or plugin workKeep it. jQuery ships with WordPress; fighting that costs more than it saves.
Adding a small script to an otherwise plain siteSkip it. querySelector and fetch cover you without a dependency.
Building a new applicationSkip it. Use React, Angular, Vue or Svelte.
Site is slow and jQuery is one of many blocking scriptsAudit it. jQuery is rarely the biggest problem, but it is often part of a wider one.
jQuery version is below 3.5Act now. Versions before 3.5 carry known XSS vulnerabilities. Upgrade regardless of your longer-term plans.

That last row is the one to take seriously. A large number of business sites are still serving jQuery 1.x or 2.x with published security advisories against them. Upgrading within the 3.x line is usually a small job and it closes a real hole.

For new work, the framework decision is a separate conversation β€” we compare the current options in choosing the best frontend framework and top frontend frameworks.


Moving off jQuery without breaking things

If you have decided to reduce your jQuery dependency, do it in stages rather than as a rewrite.

Stage 1 β€” Audit. List every place jQuery is used. Most codebases turn out to use ten or twelve methods repeatedly, not the whole library.

Stage 2 β€” Replace the easy calls. Selectors, class changes and event listeners have direct one-line equivalents. This alone often removes most usage.

Stage 3 β€” Replace plugins. This is the hard part. jQuery plugins for sliders, date pickers and modals have modern replacements, but the APIs differ and behaviour needs testing.

Stage 4 β€” Move animation to CSS. Usually a straight improvement in smoothness as well as bundle size.

Stage 5 β€” Remove the library and test properly. Automated tests earn their keep here. Our overview of JavaScript testing frameworks covers the options.

If the end goal is a component-based rewrite rather than plain JavaScript, the incremental route matters even more β€” mounting React or Angular components inside an existing page, section by section, rather than rebuilding everything at once. The pattern is the same one described in from monolith to micro frontends, and it lets the application keep serving users throughout.

Whichever route you take, measure before and after. Removing 30KB matters much less than fixing a render-blocking script or an unoptimised image, and it is worth knowing which of those you are actually dealing with β€” our guide to optimising front-end performance covers how to find out.


Frequently asked questions

Is jQuery dead? No. It runs on a large share of the web and is still actively maintained β€” jQuery 3.7 was released in 2023. It is no longer the default choice for new projects, which is different from being dead.

Do I need to learn jQuery in 2026? Not first. Learn JavaScript fundamentals and the DOM API. Learn enough jQuery to read and maintain it, because you will encounter it in existing codebases.

Is jQuery slower than vanilla JavaScript? Marginally, since jQuery methods wrap native ones. The larger cost is the download and parse time of the library itself. In most real applications, neither is the reason a page feels slow.

Can jQuery and React work on the same page? Yes, but carefully. Both want to control the DOM, and letting them touch the same elements causes unpredictable bugs. Keep them in separate, clearly bounded regions.

Which jQuery version should I use? 3.7.1 or later. Anything below 3.5 has known security vulnerabilities and should be upgraded.

Is jQuery still used in WordPress? Yes. WordPress core bundles jQuery and thousands of themes and plugins depend on it. If you work with WordPress, jQuery knowledge remains directly useful.


Where this leaves you

For learning, jQuery is still a clean introduction to selecting elements, handling events and thinking about the DOM. The concepts carry over to everything else you will use.

For building, the calculation has shifted. New projects have better options. Existing projects should be upgraded and maintained rather than rewritten on principle.

The decision that matters is not “jQuery or not” β€” it is knowing which of your pages depend on it, whether the version you are running is safe, and whether a phased migration is worth the budget. That is an audit, not a rewrite, and it usually takes a few days rather than a quarter.

If you are weighing that call on a live application, our team works on exactly this kind of legacy front-end modernisation. We will tell you plainly if the answer is “leave it alone.”