jQuery Fundamentals and DOM Manipulation

1

jQuery Fundamentals and DOM Manipulation

▶

jQuery is a fast, small, and feature-rich JavaScript library that fundamentally changed how developers interact with web pages when it was released in 2006. At its core, jQuery wraps the browser's native DOM API into a unified, cross-browser-compatible interface, letting you accomplish in one or two lines what might otherwise require ten or twenty lines of vanilla JavaScript. Even as modern JavaScript (ES6+) and browser APIs have closed the gap, jQuery remains deeply embedded in the web ecosystem. Millions of websites, WordPress themes, and enterprise applications still depend on it, making jQuery knowledge essential for any developer working with the web in a professional context.

Understanding jQuery means understanding three interconnected ideas: selecting elements from the page, manipulating those elements, and responding to user interactions — all with a concise, readable syntax that prioritizes developer productivity.

What is jQuery and Why Use It?

jQuery's philosophy is captured in its official motto: "write less, do more." To appreciate what this means in practice, compare the two approaches to hiding all paragraph elements on a page:

// Vanilla JavaScript
var paragraphs = document.querySelectorAll("p");
for (var i = 0; i < paragraphs.length; i++) {
  paragraphs[i].style.display = "none";
}

// jQuery equivalent
$("p").hide();

Both snippets produce the same result, but the jQuery version is dramatically shorter. This kind of compression pays dividends across an entire codebase — form validation, AJAX calls, animations, and event handling all benefit from jQuery's simplified API.

Beyond brevity, jQuery solves a historically painful problem: browser inconsistency. Older versions of Internet Explorer implemented many DOM and event APIs differently from Firefox, Chrome, and Safari. jQuery's internals handle those differences transparently, so your code behaves consistently everywhere without conditional branches for each browser.

Today, jQuery is less necessary for brand-new projects because modern browsers are far more consistent and ES6 introduced conveniences like querySelector, fetch, arrow functions, and template literals. Nevertheless, jQuery is still the right tool when:

  • You are maintaining or extending a legacy codebase already built with jQuery.
  • You are working with a CMS like WordPress, which ships jQuery as a core dependency.
  • You need rapid prototyping without setting up a full modern build pipeline.
  • Third-party plugins your project requires are built on jQuery.

Including jQuery via CDN

A Content Delivery Network (CDN) hosts jQuery on geographically distributed servers so that browsers can download it quickly from a nearby location. Using a CDN also means visitors who have already loaded jQuery from the same CDN on another site may have the file cached, resulting in zero download time for your page.

To include jQuery in any HTML file, add a <script> tag that points to the CDN-hosted file. This tag must appear before any of your own script tags that use jQuery, because the browser parses HTML from top to bottom and your code cannot call $ until the library is loaded.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My jQuery Page</title>
</head>
<body>

  <p>Hello, world!</p>

  <!-- 1. Load jQuery first -->
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

  <!-- 2. Then load your own script -->
  <script src="app.js"></script>

</body>
</html>

Notice the filename ends with .min.js. The minified version has had all whitespace, comments, and long variable names removed by an automated tool, shrinking the file from roughly 280 KB to about 87 KB. For production sites, always use the minified version. During development you might prefer the unminified version so that stack traces point to readable source lines, but this is optional.

Popular CDN options include the official jQuery CDN (code.jquery.com), Google Hosted Libraries, and jsDelivr. All are reliable; the choice rarely matters in practice.

Core jQuery Syntax: The $ Function

Everything in jQuery flows through a single entry point: the $ function (or equivalently jQuery — $ is simply an alias). When you write $("p"), jQuery searches the entire document for all <p> elements and returns a special jQuery object wrapping those elements. That object exposes hundreds of methods for reading, modifying, animating, and listening to those elements.

// Selecting by tag name
$("p")

// Selecting by ID (like CSS #id)
$("#main-title")

// Selecting by class (like CSS .class)
$(".highlight")

// Selecting with compound CSS selectors
$("ul.menu > li.active")

A critical concern when using jQuery is ensuring the DOM is fully parsed before your code tries to manipulate it. If a script runs while the browser is still building the page, elements you reference may not exist yet. The classic solution is $(document).ready():

$(document).ready(function() {
  // Safe to use jQuery here — DOM is fully built
  $("p").text("The DOM is ready!");
});

The shorthand form, passing a function directly to $, is functionally identical and is the style most developers prefer:

$(function() {
  $("p").text("The DOM is ready!");
});

One of jQuery's most elegant features is method chaining. Because most jQuery methods return the same jQuery object they were called on, you can attach multiple operations in a single expression without storing intermediate results:

$("p")
  .addClass("intro")      // adds class
  .css("color", "navy")   // sets color
  .hide()                 // hides element
  .fadeIn(800);           // fades it back in over 800ms

Each method in the chain executes in order on the same matched set of elements, making the code read almost like a sentence describing the sequence of operations.

Selecting and Traversing DOM Elements

jQuery selectors accept any valid CSS selector string, so everything you know about CSS targeting applies directly. Beyond that, jQuery provides traversal methods that let you navigate the DOM tree relative to an already-selected element rather than writing a fresh selector from scratch.

Here is a quick reference of the most commonly used selectors and traversal methods:

Selector / Method What It Targets Example
$("tag") All elements of that tag type $("li")
$("#id") The single element with that ID $("#header")
$(".class") All elements with that class $(".card")
.parent() Immediate parent of each matched element $("span").parent()
.children() Direct children of each matched element $("ul").children()
.siblings() All siblings of each matched element $("li.active").siblings()
.find(selector) Descendants matching a selector $("div").find("p")
.first() Only the first matched element $("li").first()
.last() Only the last matched element $("li").last()
.eq(n) Element at zero-based index n $("li").eq(2)

A practical traversal example: suppose you have a table and the user clicks a delete button inside a row. You want to remove that entire row. Using $(this) inside the click handler to reference the button, you can traverse up to the row:

$(".delete-btn").click(function() {
  $(this).closest("tr").remove();
});

.closest() walks up the DOM tree and returns the first ancestor matching the given selector — a convenient complement to .find(), which searches downward.

Modifying Content and Attributes

jQuery provides several methods for reading and writing the content and attributes of DOM elements. Most of these methods are getter/setter hybrids: called with no argument, they read; called with an argument, they write.

The .text() method works with plain text content. When reading, it returns a concatenation of all text nodes inside the matched elements, stripping any HTML tags. When writing, it replaces the element's content with the given string (HTML characters are escaped, preventing XSS):

// HTML: <p id="greeting"><strong>Hello</strong>, world!</p>

console.log($("#greeting").text()); // "Hello, world!" (tags stripped)
$("#greeting").text("Goodbye!");    // replaces content with plain text

The .html() method is the innerHTML equivalent. It preserves and injects actual HTML markup:

$("#greeting").html("<em>Welcome back!</em>");
// The element now contains an <em> tag, not escaped text

Important: never pass user-supplied data directly to .html() without sanitization — doing so opens your page to cross-site scripting attacks. Use .text() for untrusted content.

The .attr() method reads and writes any HTML attribute by name:

// Read the href of a link
var url = $("a#home-link").attr("href");
console.log(url); // e.g., "https://example.com"

// Update the src of an image
$("img#avatar").attr("src", "images/new-avatar.png");

// Set a data attribute
$("div#panel").attr("data-state", "open");

For form elements, .val() is the appropriate method for reading and setting the current value, because form inputs store user-entered text in a value property, not in their text content:

// Read what the user typed
var username = $("#username-input").val();

// Pre-fill a field
$("#search-box").val("Type here to search...");

// Clear a field
$("input[type='text']").val("");

Handling Events with jQuery

Event handling is one of jQuery's strongest areas. The library provides shorthand methods for common events, a flexible general-purpose .on() method, and built-in support for event delegation.

Shorthand methods exist for events like click, submit, keyup, mouseover, and more. They accept a callback function that runs when the event fires:

// Shorthand click handler
$("#submit-btn").click(function() {
  alert("Form submitted!");
});

// Shorthand keyup handler
$("#search-box").keyup(function() {
  console.log("You typed: " + $(this).val());
});

Inside any event handler, $(this) is a jQuery-wrapped reference to the specific element that triggered the event. This is especially useful when the same handler is attached to multiple elements:

$(".card").click(function() {
  $(this).addClass("selected"); // highlights only the clicked card
});

The .on() method is the modern, preferred approach because it is more explicit and supports multiple event types in one call:

// Attach a single event
$("#submit-btn").on("click", function() {
  alert("Clicked!");
});

// Attach multiple events with one call
$("#search-box").on("focus blur", function(event) {
  if (event.type === "focus") {
    $(this).css("border-color", "blue");
  } else {
    $(this).css("border-color", "");
  }
});

A particularly powerful feature of .on() is event delegation. When elements are added to the DOM dynamically — for example, rows added to a table after the page loads — standard handlers attached at page load won't recognize them because they didn't exist when the handler was registered. Delegation solves this by listening on a stable ancestor element and filtering events by a selector:

// Without delegation — won't work for dynamically added rows
$(".delete-btn").click(function() { ... });

// With delegation — works for all current AND future .delete-btn elements
$("#results-table").on("click", ".delete-btn", function() {
  $(this).closest("tr").remove();
});

The second argument to .on() is the delegate selector. jQuery listens for clicks anywhere inside #results-table, then checks whether the clicked element matches .delete-btn, running the callback only if it does.

Manipulating CSS and Visibility

jQuery provides several complementary tools for controlling how elements look and whether they appear on screen. The right tool depends on whether you want to apply styles inline, toggle predefined classes, or animate transitions.

The .css() method reads and writes inline CSS properties directly on elements. Property names can be written in camelCase or with quotes in CSS hyphenated form:

// Read a property
var currentColor = $("h1").css("color");

// Set a single property
$("h1").css("font-size", "2rem");

// Set multiple properties at once using an object
$(".alert").css({
  "background-color": "#ffcccc",
  "border": "1px solid red",
  "padding": "10px"
});

While .css() is convenient, it mixes style logic into JavaScript, which can make maintenance harder. A cleaner pattern is to define your styles in a CSS class and use jQuery only to toggle that class:

// CSS (in your stylesheet)
// .highlighted { background-color: yellow; font-weight: bold; }

// JavaScript — no style details here
$("td").addClass("highlighted");
$("td").removeClass("highlighted");
$("td").toggleClass("highlighted"); // adds if absent, removes if present

For controlling whether elements appear at all, .hide() sets display: none, .show() restores the previous display value, and .toggle() switches between the two states based on the current visibility:

$("#details-panel").hide();   // instantly hides
$("#details-panel").show();   // instantly shows
$("#details-panel").toggle(); // hides if visible, shows if hidden

jQuery goes a step further with animated visibility methods that produce smooth transitions automatically, without any CSS animation code:

// Fade effects
$(".notification").fadeIn(400);    // fade in over 400ms
$(".notification").fadeOut(600);   // fade out over 600ms
$(".notification").fadeToggle();   // toggle with fade

// Slide effects
$("#accordion-section").slideDown(300);   // expand downward
$("#accordion-section").slideUp(300);     // collapse upward
$("#accordion-section").slideToggle(400); // toggle with slide

The numeric argument is the duration in milliseconds. You can also pass the string "slow" (600ms) or "fast" (200ms). All animated methods also accept a callback function that fires after the animation completes, enabling you to chain behaviors:

$(".success-message")
  .fadeIn(300)
  .delay(2000)        // wait 2 seconds
  .fadeOut(500, function() {
    $(this).remove(); // remove from DOM after fade completes
  });

Bringing all of these concepts together, a typical jQuery workflow looks like this: wait for the DOM, select elements with meaningful selectors, listen for user events with .on(), and respond by traversing the DOM, reading or writing content and attributes, and applying CSS or animated visibility changes — all in a compact, readable chain of method calls that express intent clearly and concisely.

NotesIntroduces jQuery as a JavaScript library that simplifies HTML document traversal, event handling, and DOM manipulation. Demonstrates core jQuery syntax and practical examples for selecting and modifying page elements.