Episode 4 of 24

jQuery Statements and the $ Sign

Understand the jQuery function, the $ shorthand, and how jQuery statements work.

The $ sign is the heart of jQuery. It's a shorthand for the jQuery function and is used in every jQuery statement.

The $ Function

// These are identical:
jQuery("#title").hide();
$("#title").hide();

The $ is simply an alias for jQuery. Most developers use $ because it's shorter.

Basic jQuery Statement

// Pattern: $(selector).action()
$("h1").hide();          // Hide all h1 elements
$(".box").fadeIn();       // Fade in elements with class "box"
$("#main").css("color", "red");  // Change color of #main

The Three Parts

  1. $ — the jQuery function
  2. (selector) — find HTML elements (uses CSS selector syntax)
  3. .action() — perform an action on the selected elements

Document Ready

Always wrap your jQuery code in a document ready function to ensure the DOM is loaded:

// Full syntax
$(document).ready(function() {
    $("h1").text("Page is ready!");
});

// Shorthand (recommended)
$(function() {
    $("h1").text("Page is ready!");
});

The jQuery Object

// $ returns a jQuery object, not a plain DOM element
let $title = $("h1");        // jQuery object
let domTitle = $("h1")[0];    // Raw DOM element

// Convention: prefix jQuery variables with $
let $buttons = $("button");
let $sidebar = $(".sidebar");