Introduction
jQuery is a JavaScript library, first released in 2006, built around one goal: write less code to do common DOM tasks, and have it behave the same across every browser. Browsers used to disagree constantly on their JavaScript APIs — jQuery papered over those differences with one consistent interface, which is a big part of why it spread everywhere.
Loading jQuery
The simplest way to use it is a <script> tag pointing at a CDN, placed before your own script so $ is already defined when your code runs:
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script src="app.js"></script>
Once loaded, jQuery exposes a single global function, $ (also available as jQuery) — you'll use it constantly, both to select elements and to check that jQuery itself loaded.
Waiting for the page to be ready
A script tag runs the moment the browser reaches it, which can be before the rest of the page's HTML exists yet. $(document).ready() delays your code until the full DOM is parsed and safe to touch:
$(document).ready(function() {
console.log("DOM is ready, jQuery version:", $.fn.jquery);
});
DOM is ready, jQuery version: 3.7.1
In practice almost nobody writes it that verbosely — the shorthand below does exactly the same thing, and is what you'll actually see in real code:
$(function() {
console.log("Ready, shorthand version.");
});
Ready, shorthand version.
<script> tag at the very end of <body>, after the elements it references already exist in the HTML. Selecting an element that doesn't exist yet doesn't error in jQuery — it just silently returns an empty selection, which is a common source of "why isn't this working" confusion for beginners.