jQuery Syntax

jQuery syntax follows one clear shape: select elements with a dollar function, then call a method to act on them.

The basic syntax

Almost every jQuery statement starts with the dollar sign, which is a shortcut name for the jQuery function. You pass it a selector inside parentheses to choose elements, then call a method to read or change them. The general shape is: dollar sign, a selector in quotes, then an action.

The select-then-act shape

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<p>Sample paragraph</p>
<h2 id="title">Original Title</h2>
<div class="card">Card content</div>

<script>
$("p").hide();
$("#title").text("Hello");
$(".card").addClass("active");
</script>

</body>
</html>

In these three lines, the first hides every paragraph, the second sets the text of the element with the id title, and the third adds a CSS class to every element with the class card. The selector part uses the same syntax you already know from CSS.

Common selector styles

  • $("p") selects by element name, matching all paragraphs.
  • $("#header") selects by id, matching a single element.
  • $(".menu") selects by class, matching every element with that class.
  • $("*") selects every element on the page.
  • $(this) selects the current element inside an event handler.

Chaining methods together

Most jQuery methods return the same selection they were called on, so you can attach several actions in one statement. This is called chaining. It keeps related changes together and avoids selecting the same elements more than once.

Chaining several actions

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<div id="box" style="display:none;">Box content</div>

<script>
$("#box")
  .css("color", "white")
  .css("background", "navy")
  .slideDown(300);
</script>

</body>
</html>
Note: The document ready wrapper is part of everyday jQuery syntax too. Keep your statements inside it so the elements you select already exist.
SyntaxMeaningExample
$(selector)Choose elements to work with$(".item")
.method()Do something to the selection$(".item").fadeOut()
ChainingCombine actions in one line$("p").hide().fadeIn()

Exercise: jQuery Syntax

What is the general syntax pattern for a jQuery statement?