jQuery Syntax

jQuery Syntax

jQuery Syntax — $(selector).action() Explained with Examples | TipsInLearning
jQuery Lesson

jQuery Syntax

Learn the fundamental jQuery syntax pattern — how selectors work, what actions do, method chaining, the this keyword, and how to write clean professional jQuery code.

12 min read
Beginner
jQuery Basics
Free Course
What You'll Learn in This Lesson
The $(selector).action() pattern
What the $ dollar sign does
Element, ID, and class selectors
Categories of jQuery actions
Method chaining for cleaner code
this vs $(this) in event handlers

Basic jQuery Syntax

All jQuery code follows one simple pattern. Once you understand this pattern, you can read and write any jQuery statement:

$("selector").action()

This three-part pattern is the foundation of everything in jQuery. Every jQuery statement you will ever write follows exactly this structure.

$
Dollar Sign
Shorthand for the jQuery function. Gives you access to all jQuery features.
"selector"
Selector
Finds the HTML element(s) you want to work with using CSS syntax.
.action()
Action
The jQuery method to run on the selected element(s).
jQuery — Basic Examples
// Hide all paragraphs
$("p").hide();

// Change color of element with class 'highlight'
$(".highlight").css("color", "red");

// Add click event to a button
$("#myButton").click(function() {
  alert("Button was clicked!");
});

The $ Symbol

The $ is simply a shorthand alias for the word jQuery. Both are completely identical — you can use either one and get the exact same result.

jQuery — $ vs jQuery keyword
// Using $ shorthand (standard practice)
$("#myId").hide();

// Using full jQuery keyword (same result)
jQuery("#myId").hide();

// Both lines do exactly the same thing

The $ is used because it is shorter, faster to type, and is the universal industry convention. You will almost always see $ in real jQuery code.

Conflict with other libraries: Some JavaScript libraries like Prototype also use $. If you use both on the same page, call jQuery.noConflict() to release the $ shorthand and use jQuery() instead to avoid conflicts.

jQuery Selectors

Selectors are patterns that tell jQuery which HTML elements to find. jQuery uses the exact same CSS selector syntax you already know — so if you know CSS, you already know jQuery selectors.

Element, ID, and Class Selectors

jQuery — Core Selectors
// Element selector — selects ALL paragraphs
$("p")

// ID selector — selects ONE element with that id
$("#myId")

// Class selector — selects ALL elements with that class
$(".myClass")

// Multiple selectors — select all three at once
$("p, div, span")

Complex Selectors

jQuery Selector Reference
SelectorSelectsExample
element.classElement with specific class$("p.intro")
parent childAll descendants inside parent$("#myDiv p")
parent > childDirect children only$("#myDiv > p")
el + elAdjacent sibling element$("h2 + p")
s1, s2, s3Multiple elements at once$("p, div, span")
:firstFirst matched element$("p:first")
:lastLast matched element$("li:last")

jQuery Actions

Actions are the jQuery methods you call on selected elements. They are grouped into four main categories:

Effect Methods — Show, hide, animate

jQuery — Effect Methods
$("p").hide();        // Hide all paragraphs
$("p").show();        // Show all paragraphs
$("p").toggle();      // Toggle hide/show
$("p").fadeOut();    // Fade out smoothly
$("p").slideDown();  // Slide down animation

DOM Methods — Read and change content

jQuery — DOM Methods
$("p").text("New text");          // Set text
$("p").html("<b>Bold</b>");    // Set HTML
$("p").append("Added text");      // Add at end
$("p").remove();                   // Remove element

CSS Methods — Style elements

jQuery — CSS Methods
$("p").css("color", "red");        // Set CSS property
$("p").addClass("highlight");      // Add class
$("p").removeClass("highlight");   // Remove class
$("p").toggleClass("highlight");   // Toggle class

Event Methods — Handle interactions

jQuery — Event Methods
$("button").click(function() {});   // Click event
$("input").change(function() {});  // Change event
$("p").hover(function() {});       // Hover event
$("form").submit(function() {});  // Submit event

Method Chaining

jQuery allows you to chain multiple methods on the same selected element in a single statement. Instead of writing the selector multiple times, you write it once and keep adding . followed by the next method.

$("p") . hide() . fadeIn() . addClass("active")
Without Chaining — Repetitive
$("#box").hide();
$("#box").fadeIn();
$("#box").css("color","red");
$("#box").addClass("active");
With Chaining — Clean
$("#box")
  .hide()
  .fadeIn()
  .css("color", "red")
  .addClass("active");
Performance tip: Chaining is not just cleaner — it is also faster. jQuery only needs to find the element once instead of searching the DOM four separate times. For frequently used selectors, also store them in a variable like const $box = $("#box"); then use $box.hide().

The this Keyword

Inside a jQuery event handler, this refers to the specific HTML element that triggered the event. Wrap it in $(this) to use jQuery methods on it.

jQuery — this vs $(this)
$("p").click(function() {

  // 'this' = raw DOM element — use for native JS
  this.style.color = "red";
  this.innerHTML = "Clicked!";

  // '$(this)' = jQuery object — use for jQuery methods
  $(this).css("color", "red");
  $(this).hide();
  $(this).addClass("clicked");

});
ExpressionTypeUse for
thisRaw DOM elementNative JavaScript properties like this.style or this.value
$(this)jQuery objectAll jQuery methods like .css() .hide() .addClass()

Document Ready

Always wrap your jQuery code inside a document ready function. This ensures your code only runs after the entire HTML page has been loaded and parsed. If you run jQuery before the DOM is ready your selectors will find nothing.

jQuery — Document Ready (Both Versions)
// Full syntax
$(document).ready(function() {
  // All your jQuery code goes here
  $("p").click(function() {
    $(this).hide();
  });
});

// Shorthand — most commonly used
$(function() {
  // Same thing — shorter to write
  $("p").click(function() {
    $(this).hide();
  });
});

jQuery vs Vanilla JavaScript

Here is a side-by-side comparison showing how much shorter jQuery makes common tasks:

TaskVanilla JavaScriptjQuery
Select by IDdocument.getElementById("id")$("#id")
Select by classdocument.querySelectorAll(".class")$(".class")
Hide elementel.style.display = "none"$(sel).hide()
Get textel.textContent$(sel).text()
Add classel.classList.add("class")$(sel).addClass("class")
Click eventel.addEventListener("click", fn)$(sel).click(fn)

Best Practices

Cache your selectors in variables

jQuery — Caching Selectors
// Good — select once, use many times
const $box = $("#myBox");
$box.hide();
$box.fadeIn();
$box.css("color", "red");

// Bad — searching DOM three separate times
$("#myBox").hide();
$("#myBox").fadeIn();
$("#myBox").css("color", "red");

Use proper formatting for readability

jQuery — Clean Code Formatting
// Good — readable and well formatted
$(function() {
  $("button").click(function() {
    $(this)
      .hide()
      .fadeIn()
      .css("color", "red");
  });
});

// Bad — impossible to read
$(function(){$("button").click(function(){$(this).hide().fadeIn().css("color","red");});});

Try It Yourself

Practice everything from this lesson by building this interactive page:

Challenge — jQuery Syntax Practice
1Create a page with jQuery loaded via CDN. Add 3 paragraphs and a button. Write $("p").hide() inside document ready and confirm all paragraphs hide on load
2Add a click event to the button using $("button").click() that shows the paragraphs again with $("p").show()
3Use $(this) inside a paragraph click handler to hide only the paragraph that was clicked
4Practice method chaining — select #myDiv and chain at least 3 methods like .css().addClass().fadeIn()
5Store a selector in a variable like const $btn = $("button") and use it three times without rewriting the selector
Lesson Summary — Key Takeaways
1jQuery syntax is always $(selector).action() — three parts every time
2$ is shorthand for jQuery — both do exactly the same thing
3Selectors use CSS syntax — #id .class and tag names
4Chain methods with dots to run multiple actions without repeating the selector
5$(this) wraps the current event element so you can use jQuery methods on it
6Always wrap code in $(function(){...}) to wait for the DOM to load

Frequently Asked Questions

Common questions beginners ask about jQuery syntax:

The basic jQuery syntax is dollar sign open bracket selector close bracket dot action open bracket close bracket. The dollar sign gives you access to jQuery, the selector finds the HTML elements you want using CSS syntax, and the action is the jQuery method you want to run on those elements. Every jQuery statement follows this exact same three-part pattern.

The dollar sign is simply a shorthand alias for the jQuery function. Writing dollar sign open bracket selector close bracket and jQuery open bracket selector close bracket do exactly the same thing. The dollar sign is used because it is shorter, faster to type, and is the universal standard in the jQuery community. If another library also uses dollar sign you can call jQuery.noConflict() to resolve the conflict.

jQuery selectors use CSS selector syntax to find and select HTML elements on the page. Hash id selects by id, dot class selects all elements with that class name, and just the tag name selects all elements of that type. You can also combine selectors for more specific matches such as p dot intro to select only paragraphs that also have the intro class.

Method chaining lets you call multiple jQuery methods on the same selected element in a single statement without repeating the selector. You write the selector once and chain additional methods using dots. This is both cleaner to read and better for performance because jQuery only searches the DOM once instead of multiple times for the same element.

Inside a jQuery event handler, this is the raw JavaScript DOM element that triggered the event. You can use it to access native JavaScript properties like this.style or this.value. Dollar sign this wraps that DOM element in a jQuery object so you can call jQuery methods on it like dot css or dot addClass or dot hide. Always use dollar sign this when you want to use jQuery methods on the current element.

Wrapping your jQuery code inside document ready ensures it only runs after the entire HTML page has finished loading. If you run jQuery code before the DOM is ready your selectors will find no elements because the HTML has not been parsed yet. The shorthand version is dollar sign open bracket function open bracket close bracket open bracket your code here close bracket close bracket.

Post a Comment