What you'll learn
What jQuery is, how to load it, and how the $ function selects elements.
Why it matters
Millions of existing websites run on jQuery, and you will meet it in older codebases, WordPress themes and plugins. Knowing it lets you read and maintain that code.
Explanation
jQuery is a small JavaScript library: pre-written code you include in your page. It gives you short commands for selecting elements, changing them, reacting to clicks and animating.
Everything starts with the $ function (also called jQuery). You give it a CSS selector and it returns a collection of matching elements that you can act on.
$("p").css("color", "tomato");That reads: find all paragraphs, then set their colour to tomato.
Your code should wait until the page is ready. The usual way is:
$(function () {
// your code here runs when the HTML has loaded
});Example
<h1>Hello</h1>
<p>First paragraph.</p>
<p>Second paragraph.</p>
<script>
$(function () {
$("p").css("color", "tomato");
$("h1").text("Hello from jQuery");
});
</script>Step-by-step walkthrough
- The runner on this page has already loaded jQuery for you. In your own pages you add a
<script src="...jquery.min.js">tag first. $(function () { ... })waits until the HTML is ready.$("p")selects both paragraphs..css("color", "tomato")colours them.$("h1").text(...)replaces the heading text.
Try it yourself
Change the colour, and select only the first paragraph using $("p").first().
Common mistakes
- Running code before the page is ready, so
$("p")finds nothing. - Forgetting to load jQuery (or loading it after your script).
- Selector typos. Use
.classand#idlike CSS. - Assuming jQuery is required today. Modern browsers do most of this natively. We cover that in a later lesson.
Quick quiz
Summary
- jQuery is a JavaScript library;
$("selector")selects elements. - Methods like
.css()and.text()act on the selection. - Wrap code in
$(function () { ... })to run when the page is ready.
Next: selectors in detail.