jQuery Syntax

Understand the select-then-act pattern behind every jQuery statement.

Syntax$( selector ).method( arguments );

Almost all jQuery follows one pattern: select elements with $(), then act on them with a method.

Anatomy of a jQuery statement$("p.intro").hide(400);selector (what)method (do)argument (how)
Every jQuery statement: select elements, then call a method on them.

Reading the pattern

  • $ — the jQuery function (also called jQuery).
  • ("p.intro") — a CSS-style selector for the elements you want.
  • .hide(400) — the action to perform, with an optional argument.

The result of $() is a jQuery object — a wrapped set of elements you can chain methods on.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A developer uses the $(selector).method() pattern to apply a fade effect to every .card element at once.
  • A menu script chains multiple methods on $("#nav") to hide, update text, and re-show in one statement.
  • A data table plugin calls $(".row").filter() then .addClass() using the select-then-act pattern.

More examples

Select by class and act

A single class selector matches all .note elements and .css() applies to every one simultaneously.

Example · html
<p class="note">First note</p>
<p class="note">Second note</p>
<script>
$(function () {
  $(".note").css("color", "steelblue");
});
</script>

Select by id and chain methods

Method chaining applies multiple actions to the same matched set without re-selecting the element.

Example · html
<div id="banner">Welcome</div>
<script>
$(function () {
  $("#banner")
    .css("background", "#222")
    .css("color", "#fff")
    .fadeIn(600);
});
</script>

Attribute selector narrows match

An attribute selector inside $() narrows the match to only text inputs, then .val() sets their value.

Example · html
<form>
  <input type="text" name="email" />
  <input type="submit" value="Send" />
</form>
<script>
$(function () {
  $("input[type='text']").val("[email protected]");
});
</script>

Discussion

  • Be the first to comment on this lesson.