Unit 6 · 17 min read
Introduction to jQuery
What the syllabus asks for 9
- Setting up
- Selectors and filtering
- Getting and setting content, attributes, CSS, classes
- Adding, removing and cloning elements
- Events
- Effects and chaining
- AJAX with jQuery
- jQuery versus plain JavaScript
- Seeing jQuery: selection, chaining, effects and traversal
jQuery is a small JavaScript library that makes selecting elements, changing the page, handling events and calling the server shorter and consistent across browsers. Its motto: write less, do more.
Modern JavaScript has absorbed many of its features, but jQuery is still on millions of sites and is part of this syllabus.
- Including jQuery and the
$function,ready. - Selecting and filtering elements; getting and setting content, attributes, CSS and classes.
- Adding and removing elements, events, effects, chaining, AJAX.
- Every example below was run in a simulated browser (jsdom) with jQuery 3; the output is real.
6.1 Setting up
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () { // or the short form: $(function () { ... });
$("#hello").text("jQuery is ready");
});
</script>
Load jQuery from a CDN or your own copy before your script. $ is an alias of jQuery: $(selector) returns a jQuery object wrapping all matching elements; $(function(){…}) runs the code when the DOM is ready. The basic pattern is select → act: $(selector).action().
6.2 Selectors and filtering
jQuery uses CSS selectors (Unit 4) plus extras.
<ul id="list">
<li class="item">One</li>
<li class="item done">Two</li>
<li class="item">Three</li>
<li class="other">Four</li>
</ul>
//---
console.log($("li").length); // by tag
console.log($(".item").length, $("#list").length); // by class, by id
console.log($("li.done").text()); // combined
console.log($("#list > li").first().text(), $("li").last().text());
console.log($("li").eq(2).text()); // index 2
console.log($("li").not(".item").text()); // exclusion
console.log($("li:even").length); // even positions (0, 2)
console.log($(".done").prev().text(), $(".done").next().text());
console.log($("li").filter(function () { return $(this).text().length > 3; }).length);
4
3 1
Two
One Four
Three
Four
2
One Three
2
$("li").length counts matches (0 if none: always safe). Other helpers: .parent(), .children(), .siblings(), .find("p") (descendants), .closest(".box").
6.3 Getting and setting content, attributes, CSS, classes
| Method | Use |
|---|---|
.text(), .html(), .val() |
get/set text, HTML, form value |
.attr("href"), .prop("checked"), .data("id") |
attribute, property, data-* |
.css("color", "red") |
inline style (getter with one argument) |
.addClass(), .removeClass(), .toggleClass(), .hasClass() |
class manipulation (preferred to .css) |
<h1 id="title">Old title</h1>
<a id="link" href="http://old.example" data-id="42">link</a>
<input id="name" value="Sita">
<p class="msg">message</p>
//---
$("#title").text("New title");
console.log($("#title").text());
console.log($("#link").attr("href"), $("#link").data("id"));
$("#link").attr("href", "https://new.example");
console.log($("#link").attr("href"));
console.log($("#name").val());
$("#name").val("Ram");
console.log($("#name").val());
$(".msg").addClass("big important").css({ color: "red", "font-size": "20px" });
console.log($(".msg").hasClass("big"), $(".msg").attr("class"), $(".msg").css("color"));
$(".msg").toggleClass("big");
console.log($(".msg").attr("class"));
$("#title").html("<em>Styled</em> title");
console.log($("body").html().replace(/\s+/g, " ").slice(0, 60));
New title
http://old.example 42
https://new.example
Sita
Ram
true msg big important rgb(255, 0, 0)
msg important
<h1 id="title"><em>Styled</em> title</h1> <a id="link" href=
6.4 Adding, removing and cloning elements
.append() / .prepend() add inside at the end / start; .after() / .before() add outside; .remove() deletes the element, .empty() clears its children; .clone() copies; .wrap(), .replaceWith(). .each(function (i, el) { … }) loops over matches.
<ul id="menu"><li>Home</li><li>Courses</li></ul>
//---
$("#menu").append("<li>Contact</li>").prepend("<li class='first'>Logo</li>");
console.log($("#menu li").length, $("#menu li:first").text());
$("#menu li").last().after("<li>Footer</li>");
$("#menu li:contains('Courses')").remove();
$("#menu li").each(function (i) { $(this).text((i + 1) + ". " + $(this).text()); });
console.log($("#menu").text());
const copy = $("#menu").clone();
console.log(copy.find("li").length, $("#menu").find("li").length);
$("#menu").empty();
console.log($("#menu").children().length);
4 Logo
1. Logo2. Home3. Courses4. Contact5. Footer
5 5
0
6.5 Events
.on(event, [selector], handler) attaches; .off() removes; shortcuts include .click(), .hover(), .submit(), .keyup(), .change(). Inside a handler, this is the element and e.preventDefault() / e.stopPropagation() are available.
Delegated form $("#list").on("click", "li", fn) also works for elements added later. .trigger("click") fires an event from code.
<button id="inc">+1</button> <span id="count">0</span>
<ul id="todo"><li>A</li></ul>
//---
let clicks = 0;
$("#inc").on("click", function () { clicks++; $("#count").text(clicks); });
$("#inc").trigger("click").trigger("click").trigger("click");
console.log("count shows", $("#count").text());
$("#todo").on("click", "li", function () { $(this).toggleClass("done"); });
$("#todo").append("<li>B (added later)</li>");
$("#todo li").last().trigger("click");
console.log($("#todo li.done").text());
$("#inc").off("click");
$("#inc").trigger("click");
console.log("after off:", $("#count").text());
count shows 3
B (added later)
after off: 3
6.6 Effects and chaining
Effects: .show(), .hide(), .toggle(), .fadeIn(), .fadeOut(), .slideUp(), .slideDown(), and .animate({height: "200px", opacity: .5}, 500). Each accepts a duration (ms) and a callback run when it finishes.
Chaining works because most methods return the jQuery object: $("#box").addClass("on").fadeIn(300).text("Done");.
<div id="box">Hello</div>
//---
$("#box").hide();
console.log("display after hide():", $("#box").css("display"));
$("#box").show();
console.log("display after show():", $("#box").css("display"));
$("#box").addClass("on").css("color", "green").text("Done");
console.log($("#box").text(), $("#box").attr("class"), $("#box").css("color"));
display after hide(): none
display after show(): block
Done on rgb(0, 128, 0)
6.7 AJAX with jQuery
AJAX (Asynchronous JavaScript And XML) requests data from the server in the background and updates part of the page without a reload. jQuery wraps it:
$("#result").load("notice.html #latest"); // fetch HTML fragment into an element
$.get("/api/students", function (data) { ... }); // GET
$.post("/api/students", { name: "Sita" }, function (res) { ... });
$.ajax({
url: "/api/students/1", method: "GET", dataType: "json",
success: function (s) { $("#name").text(s.name); },
error: function (xhr, status) { alert("Failed: " + status); }
});
// modern equivalent without jQuery:
fetch("/api/students/1").then(r => r.json()).then(s => { document.getElementById("name").textContent = s.name; });
These calls need a real server, so they are shown but not executed here. Browsers apply the same-origin policy: a page may call only its own origin unless the server allows others with CORS headers. $.getJSON(url, cb) is shorthand for a JSON GET.
6.8 jQuery versus plain JavaScript
| Task | jQuery | Modern JavaScript |
|---|---|---|
| Select | $(".item") |
document.querySelectorAll(".item") |
| Text | $("#a").text("x") |
document.querySelector("#a").textContent = "x" |
| Class | .addClass("on") |
el.classList.add("on") |
| Event | .on("click", f) |
el.addEventListener("click", f) |
| AJAX | $.get(url, cb) |
fetch(url).then(r => r.json()) |
jQuery's benefits are brevity and old-browser compatibility; its cost is an extra download (about 30 KB gzipped). New projects usually use plain JavaScript or frameworks, but legacy code and WordPress themes still rely on jQuery.
6.9 Seeing jQuery: selection, chaining, effects and traversal
jQuery wraps the DOM in a short, chainable API.
The plate shows its creator and a timeline; the figures show how a selector picks elements, how a chain passes one object along, how the animation queue adds up in milliseconds, how traversal walks the tree and how an AJAX call is split into a request and a callback.
In the figures the function is written jQuery(...), which is exactly the same function as the dollar shorthand used in the code.

6.9.1 Eight reasons to use jQuery, and when to avoid it
- Short code for common jobs. One line such as
$("li.done").hide()selects many elements and acts on all of them. The same job in older plain JavaScript needed a loop and several checks. A college notice page with hundreds of rows can be filtered with a line or two. - Browser differences are hidden. jQuery was built when browsers disagreed about events, styles and AJAX, and it gave one behaviour everywhere. Old sites in schools and offices still run on older browsers. Using the library meant the same script worked for every visitor.
- Powerful selectors and traversal. CSS-style selectors, filters such as
:firstand:even, and methods such asclosest()andfind()make it easy to reach any element. A delete button can find its own table row without knowing a row number. This keeps the code short and independent of the layout. - Method chaining. Each call returns the jQuery object, so selecting, styling and animating can be done in one statement. The chain is read from left to right like a sentence. It also avoids selecting the same element repeatedly.
- Built-in effects.
fadeIn,slideToggleandanimateadd smooth motion without writing timers. A Nepali news site can open and close a menu or notice with a slide. The queue runs the effects in order, as shown in Figure 6.3. - Simple AJAX.
$.get,$.post,$.getJSONand$.ajaxsend background requests with promise methods for success and failure. A form can be submitted and a message shown without reloading the page. This was a big step for Web 2.0 style pages. - Plugins and an ecosystem. Date pickers, sliders, data tables and validation plugins are available for jQuery and plug into the same selector style. Many admin templates used by Nepali software companies still include them. Reusing a tested plugin saves days of work.
- When to avoid it. Modern JavaScript offers
querySelectorAll,classList,fetchand arrow functions, and frameworks such as React and Vue manage the page themselves. A new small project may not need the 87 KB (about 30 KB compressed) library. Keep jQuery for maintaining existing sites and for quick scripts, and learn the plain DOM first.

Formula and fact sheet
- Pattern:
$(selector).action();$(function(){ … })runs on DOM ready. - Get/set:
.text() .html() .val() .attr() .css(); classes:.addClass() .removeClass() .toggleClass(). - DOM:
.append() .prepend() .after() .before() .remove() .empty() .clone() .each(). - Events:
.on(event, [selector], fn),.off(),.trigger(). - Effects:
.show() .hide() .fadeIn() .slideUp() .animate(); chaining returns the jQuery object. - AJAX:
$.get,$.post,$.ajax,.load.
Chapter summary
- jQuery selects elements with CSS selectors and applies short methods to all matches.
- It reads and writes content, attributes and styles, builds and removes DOM nodes, and handles events (including delegated ones).
- Effects and chaining make UI code compact; AJAX helpers load data without a page reload.
Practice
- Explain
$and$(document).ready(). - Write jQuery to hide all paragraphs with class
tipwhen a button#hideis clicked. - Write code to add a new
<li>with text "Item" to#listand change the colour of everylito blue. - Differentiate
.text()and.html();.remove()and.empty(). - Explain event delegation in jQuery with an example.
- What does chaining mean? Write a chained statement.
- Write an AJAX GET that puts the response text into
#out. - Give two reasons to prefer modern JavaScript over jQuery in a new project.
Answers and worked solutions
1. $ is an alias for jQuery; $(document).ready(fn) runs fn once the DOM is fully built so elements can safely be selected.
2. $("#hide").on("click", function () { $("p.tip").hide(); });
3. $("#list").append("<li>Item</li>"); $("#list li").css("color", "blue");
4. .text() reads/sets plain text; .html() reads/sets HTML markup. .remove() deletes the element itself; .empty() deletes only its children.
5. $("#list").on("click", "li", fn) attaches one handler to the list that runs for any current or future li clicked, via event bubbling.
6. Calling several methods in one statement because each returns the jQuery object: $("#box").addClass("on").fadeIn(200).text("Hi");
7. $.get("/data.txt", function (t) { $("#out").text(t); });
8. Browsers now provide querySelector, classList, fetch and addEventListener; skipping jQuery saves a download and avoids another dependency.
Model answers: medium (5 marks) and long (10 marks) questions
Q1 (5 marks). What is jQuery? Explain its selectors and the basic syntax with examples.
Introduction. jQuery is a fast, small JavaScript library that simplifies selecting elements, handling events, animating and sending AJAX requests; its basic form is $(selector).action() (sections 6.1 and 6.2, Figure 6.1).
- Setting up. Include the library with a script tag (a local file or a CDN) and put code inside
$(document).ready(function () { ... })or its short form$(function () { ... }), so it runs after the DOM is loaded. - Basic selectors.
$("p")by element,$(".done")by class,$("#menu")by id,$("ul li")descendants,$("ul > li")direct children,$("a, b")groups. - Attribute selectors.
$("input[type='text']")and$("a[href^='https']")select by attribute value. - Filters.
:first,:last,:even,:odd,:not(.done),:eq(2)and:contains("Nepal")narrow a set; indexes start at 0. - The result. A jQuery object that acts like an array:
.lengthgives the number matched, and methods apply to every match. - Syntax of an action.
$("#msg").text("Saved"),$("p").addClass("big")and$(".row").hide().
<script>
$(function () {
$("li.done").css("color", "green");
$("ul > li:first").addClass("first");
alert($("li").length + " items");
});
</script>
Conclusion. A jQuery statement selects elements with a CSS-like selector and applies an action to all of them, which makes common DOM tasks one-liners.
Q2 (5 marks). Compare jQuery with plain JavaScript. Write the jQuery equivalent of a given plain JavaScript snippet and explain method chaining.
Introduction. jQuery is written in JavaScript, so everything it does can also be done without it; the difference is in the amount of code and in browser support (section 6.8, Figures 6.1 and 6.2).
- Selecting and acting. Plain:
document.querySelectorAll(".done").forEach(function (e) { e.style.display = "none"; });. jQuery:$(".done").hide();. - Events. Plain:
el.addEventListener("click", fn)on one element. jQuery:$("button").on("click", fn)on every matching element at once. - AJAX. Plain:
fetch(url).then(r => r.json()).then(show). jQuery:$.getJSON(url, show). - Chaining. Methods return the jQuery object, so
$("#box").addClass("on").css("color", "red").fadeOut(400)runs three actions after one search of the page. - Cost. jQuery adds about 87 KB (30 KB compressed) and a small speed cost, while modern browsers support nearly everything natively.
| Point | jQuery | Plain JavaScript |
|---|---|---|
| Code length | Short | Longer |
| Browser differences | Hidden | Modern browsers agree |
| Page weight | Adds about 87 KB | None |
| Best for | Maintaining older sites, quick scripts | New projects |
Conclusion. jQuery saves code and hides old browser problems, but plain JavaScript is now enough for most new work; chaining is its most useful idea.
Q3 (10 marks). Explain AJAX with jQuery. Write a program that fetches a student's result as JSON when a button is clicked and shows it in a table, with error handling. Name the jQuery AJAX methods.
Introduction. AJAX (Asynchronous JavaScript and XML) lets a page request data from a server in the background and update only part of the page.
It avoids reloading and makes web pages behave like applications. jQuery wraps the browser's XMLHttpRequest in short methods (section 6.7, Figure 6.5).
- load().
$("#box").load("part.html")fetches an HTML fragment and inserts it into the element. $.get()and$.post().$.get(url, data, callback)sends a GET request and$.post(url, data, callback)a POST request with the data in the body.$.getJSON(). It fetches JSON and passes the parsed object to the callback.$.ajax(). The general form takes an object with url, method, data, dataType, success, error and timeout; every shortcut calls it.- Promises. The calls return an object with
.done()for success,.fail()for error and.always()for both, which keeps code readable. - Asynchronous behaviour. The statement after the call runs immediately, before the answer arrives; code that needs the data must be inside the callback.
- Security. Browsers block requests to other origins unless the server allows them with CORS headers. Never insert server text with
.html()without cleaning it;.text()is safe. - User feedback. Show a loading message and hide it in
.always().
<input id="roll" value="101"> <button id="go">Show result</button>
<p id="status"></p>
<table id="res"><tbody></tbody></table>
<script>
$("#go").on("click", function () {
$("#status").text("Loading...");
$.getJSON("/api/results", { roll: $("#roll").val() })
.done(function (r) {
$("#res tbody").html("<tr><td></td><td></td></tr>");
$("#res td:first").text(r.name);
$("#res td:last").text(r.marks);
})
.fail(function () { $("#status").text("Could not load the result."); })
.always(function () { if ($("#status").text() === "Loading...") $("#status").text(""); });
});
</script>
| Method | Purpose | Returns data as |
|---|---|---|
| load() | Insert HTML into an element | HTML text |
$.get() |
GET request | Text or object |
$.post() |
POST request | Text or object |
$.getJSON() |
GET JSON | JavaScript object |
$.ajax() |
Full control | Any type |
Conclusion. jQuery AJAX sends a request, continues at once and runs a callback when the answer comes, so only the needed part of the page changes. .done(), .fail() and .always() give a clear way to handle success, errors and cleanup.