jQuery Basics — Complete Setup, Syntax & Document Ready Guide
jQuery is a fast, lightweight JavaScript library that simplifies HTML document manipulation, event handling, animations, and AJAX requests with an easy-to-use API.
What You’ll Learn
- What jQuery is and why developers use it
- How to include jQuery via CDN or download
- The
$function syntax and how selectors work - The document ready pattern and why it matters
- Method chaining and the jQuery object
- How to avoid common jQuery beginner mistakes
Why jQuery Basics Matters
Every jQuery journey starts here. Think of jQuery as a power tool for web development — you wouldn’t use a screwdriver to drive a hundred nails, right? jQuery turns complex JavaScript tasks into one-liners. At DodaTech, tools like Durga Antivirus Pro’s admin dashboard UI use jQuery for DOM manipulation, event handling, and AJAX calls to load real-time threat data. Understanding jQuery basics lets you work on such projects and maintain legacy systems still running on it.
jQuery Learning Path
flowchart LR
A[HTML & CSS Basics] --> B[jQuery: You Are Here]
B --> C[jQuery Selectors]
C --> D[jQuery Events]
D --> E[jQuery DOM Manipulation]
E --> F[jQuery Effects]
F --> G[AJAX & APIs]
What Is jQuery?
Let’s start with the big question: Why does jQuery exist?
Back in 2006, JavaScript was a mess. Different browsers had different APIs. getElementById worked everywhere, but everything else was a minefield. jQuery stepped in and said: “Write one line, it works everywhere.” It wrapped all the complexity into a single function — the $ — and gave developers superpowers.
Think of jQuery like a universal remote control. Instead of walking up to each device (the TV, the soundbar, the streaming stick) and pressing its individual buttons, you use one remote that talks to everything. jQuery talks to every browser the same way.
How jQuery Works
flowchart LR
A[HTML Page] --> B[jQuery Library Loads]
B --> C[$(selector) Creates jQuery Object]
C --> D[.method() Performs Action]
D --> E[Returns jQuery Object → Chaining]
E --> C
Including jQuery
You need to load the jQuery library before any code that uses it. There are two ways:
Method 1: CDN (Recommended)
A CDN (Content Delivery Network) serves jQuery from servers near your user, making it load faster:
<!-- Google CDN (most common) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<!-- jsDelivr CDN (alternative, equally good) -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>Method 2: Download Locally
Download from jquery.com and serve from your own server:
<script src="js/jquery-3.7.1.min.js"></script>Why CDN over download? The CDN version is likely already cached in your user’s browser (many sites use Google’s jQuery CDN), so the file loads instantly — zero download time.
Complete Page Setup
Always load jQuery before your custom scripts. Here’s the correct order:
<!DOCTYPE html>
<html>
<head>
<title>My First jQuery Page</title>
</head>
<body>
<h1>Hello, jQuery!</h1>
<p class="message">This paragraph will change color.</p>
<!-- Step 1: Load jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<!-- Step 2: Your code using jQuery -->
<script>
$(document).ready(function() {
$("h1").css("color", "blue");
$(".message").css("font-weight", "bold");
});
</script>
</body>
</html>Let’s break down that script line by line:
$(document).ready(function() { ... })— This waits for the HTML document to finish loading before running the code inside. Why? Because if you try to select$("h1")before the<h1>element exists in the browser’s memory, jQuery finds nothing.$("h1")— Selects all<h1>elements on the page..css("color", "blue")— Changes the CSScolorproperty to blue.$(".message")— Selects all elements withclass="message"..css("font-weight", "bold")— Makes their text bold.
The $ Function: jQuery’s Entry Point
The $ is just an alias for jQuery. They’re the same thing:
// These two lines are 100% identical
$("p").hide();
jQuery("p").hide();Why do we use $? It’s short. You’ll type it hundreds of times per page, so saving 5 characters per call adds up fast.
What Does $(selector) Return?
It returns a jQuery object — a collection of matched DOM elements with all jQuery methods attached. Think of it as a gift box: the DOM elements are inside, but the box itself has useful tools (methods) built into it.
// Select all paragraphs — returns a jQuery object
var $paragraphs = $("p");
// The jQuery object has a .length property
console.log($paragraphs.length); // How many <p> elements exist?
// Access the raw DOM element inside (unwrap the box)
var firstParagraph = $paragraphs[0]; // Native DOM element
// Check if any elements were found
if ($("#myId").length) {
console.log("Element exists!");
}Why Check .length?
This is a pattern you’ll use constantly. If no elements match your selector, jQuery returns an empty jQuery object — not an error. So calling .hide() on an empty object does nothing silently. By checking .length, you verify your selection actually found something.
The Document Ready Pattern
Here’s the most important jQuery rule: Never manipulate the DOM before it’s fully loaded.
Think of it like this: you can’t decorate a room before the walls are built. If you run jQuery code before the browser has parsed the HTML, those elements don’t exist yet.
// Full form — explicit and clear
$(document).ready(function() {
// jQuery code here — DOM is fully parsed
console.log("The DOM is ready!");
});
// Short form — used in 99% of real code
$(function() {
// jQuery code here
});The short form does exactly the same thing. Use it — it’s the standard in professional code.
Multiple Ready Blocks
You can have several $(function(){}) blocks on the same page. They run in order:
$(function() {
$("header").css("background", "#333");
});
$(function() {
$("footer").css("background", "#111");
});Each block waits for the DOM to be ready. This is useful when you have separate scripts that each need to initialize independently.
Method Chaining
This is where jQuery’s elegance shines. Most jQuery methods return the jQuery object itself, so you can call multiple methods in a row:
// Without chaining — repetitive and slower
$("#myDiv").css("color", "red");
$("#myDiv").slideUp(1000);
$("#myDiv").slideDown(1000);
// With chaining — clean, fast, readable
$("#myDiv")
.css("color", "red")
.slideUp(1000)
.slideDown(1000);How does this work? Each method (.css(), .slideUp(), .slideDown()) modifies the element and then returns the jQuery object. The next method in the chain picks up where the last one left off.
Caveat: Some methods don’t return the jQuery object — they return a value. For example, .width(), .height(), and .text() (when getting, not setting) break the chain.
JavaScript vs jQuery Comparison
| Task | Vanilla JavaScript | jQuery |
|---|---|---|
| Select an element by ID | document.getElementById("myId") | $("#myId") |
| Change text content | el.textContent = "Hello" | $("#myId").text("Hello") |
| Add a class | el.classList.add("active") | $("#myId").addClass("active") |
| Wait for DOM ready | document.addEventListener("DOMContentLoaded", fn) | $(fn) |
| Get element height | el.clientHeight | $("#myId").height() |
Notice something? jQuery lines are shorter and read more like English sentences. That’s the appeal.
Common Mistakes
1. Running jQuery Code Before the Library Loads
If jQuery isn’t loaded when your script runs, $ is undefined:
// This causes: Uncaught ReferenceError: $ is not defined
$("p").hide();Fix: Load jQuery via CDN before your <script> tags. Check your network tab in DevTools to confirm it loaded.
2. Forgetting Document Ready
// WRONG — runs before DOM is parsed, finds nothing
$("button").click(function() { alert("Clicked!"); });
// RIGHT — waits for DOM
$(function() {
$("button").click(function() { alert("Clicked!"); });
});3. Not Checking If Elements Exist
$("#nonexistent").hide(); // No error, but also does nothing
// Always verify:
if ($("#nonexistent").length) {
// Safe to work with the element
}4. Mixing jQuery and Native DOM Methods
var $el = $("#myDiv");
// $el.innerHTML = "text"; // WRONG — $el is a jQuery object, not a DOM element
$el.html("text"); // RIGHT — jQuery method
$el[0].innerHTML = "text"; // ALSO RIGHT — unwrap to native DOM element
5. Using $ in Browser Console Expecting jQuery
In modern browsers, $ in the console is document.querySelector(), not jQuery. If you need the full jQuery API in the console, wrap your expression: jQuery("p").hide().
6. Not Using the Minified Version in Production
<!-- Development: readable, debuggable -->
<script src="jquery-3.7.1.js"></script>
<!-- Production: smaller, faster -->
<script src="jquery-3.7.1.min.js"></script>The minified version is 50-70% smaller. Always use it on live sites.
Practice Questions
1. What does the $ function return?
It returns a jQuery object — a collection of matched DOM elements wrapped with jQuery methods.
2. Why do we wrap code in $(function() { ... })?
To wait for the DOM to finish loading before executing jQuery. Without it, selectors may find no elements because the HTML hasn’t been parsed.
3. What is method chaining and how does it work?
Calling multiple methods on the same jQuery object in sequence. It works because most jQuery methods return the jQuery object itself.
4. Which loads first: jQuery library or your custom script?
jQuery must load first. The <script> tag for jQuery goes before your custom script tag.
5. Challenge: Create a page that has 3 paragraphs. When the page loads, make the first paragraph red, the second paragraph bold, and the third paragraph hidden — all with jQuery chaining on a single selection.
Answer
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(function() {
$("p")
.eq(0).css("color", "red").end()
.eq(1).css("font-weight", "bold").end()
.eq(2).hide();
});
</script>FAQ
Try It Yourself
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Basics Sandbox</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 600px; margin: 40px auto; text-align: center; }
.box { padding: 20px; margin: 10px; background: #e3f2fd; border-radius: 8px; display: none; }
button { padding: 10px 20px; margin: 5px; cursor: pointer; }
</style>
</head>
<body>
<h1 id="title">jQuery Basics Sandbox</h1>
<p class="message">Click the button to reveal the hidden box.</p>
<button id="showBtn">Show Box</button>
<div class="box">
<p>This box was hidden and revealed with jQuery!</p>
<p>Current time: <span id="time"></span></p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(function() {
// Set the time in the hidden box
$("#time").text(new Date().toLocaleTimeString());
// Handle button click
$("#showBtn").click(function() {
$(".box")
.css("background", "#c8e6c9")
.slideDown(500);
$(this).text("Shown!").prop("disabled", true);
});
// Hover effect on title
$("#title").hover(
function() { $(this).css("color", "#1a73e8"); },
function() { $(this).css("color", "black"); }
);
});
</script>
</body>
</html>What’s Next
| Topic | Description |
|---|---|
| https://tutorials.dodatech.com/frameworks/jquery/jquery-selectors/ | Learn how to precisely target DOM elements with selectors |
| https://tutorials.dodatech.com/frameworks/jquery/jquery-events/ | Handle user interactions like clicks and keypresses |
| https://tutorials.dodatech.com/frameworks/jquery/jquery-dom/ | Master DOM manipulation with jQuery |
| JavaScript | Core JavaScript fundamentals every jQuery developer needs |
| HTML | HTML structure and semantic markup |
What’s Next
Congratulations on completing this Jquery Basics tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro