TExcelTAD
Home › jQuery › jQuery Syntax

jQuery Syntax

Nearly every line of jQuery follows the same pattern: select some elements, then do something with them.

js
$(selector).action(arguments);
Part Meaning
$ The jQuery function (an alias of jQuery)
(selector) A CSS selector string that finds elements — or an element, or HTML to create
.action() A jQuery method applied to every matched element

Some examples:

js
$("p").hide();              // hide every <p>
$(".warning").show();       // show elements with class="warning"
$("#title").text("Hi");    // set the text of the element with id="title"
$(this).addClass("active"); // inside an event handler: the clicked element

The document ready event

Code that touches the page must wait until the elements exist. jQuery's ready handler runs your function as soon as the HTML has been parsed (it does not wait for images, unlike window.onload).

js
// recommended short form
$(function () {
  // your code here
});

// long form, same meaning
$(document).ready(function () {
  // your code here
});

Note: In jQuery 3 the $(document).on("ready", fn) form was removed. Use $(fn). If the DOM is already ready when you register a handler, jQuery still runs it (asynchronously).

What can go inside $()

The jQuery function is overloaded — what it does depends on the argument:

Call Result
$("ul li") Find elements matching a CSS selector
$("li", list) Find matching elements inside list
$(element) Wrap an existing DOM element (e.g. this)
$("<li>New</li>") Create new elements from an HTML string
$(function () {…}) Run the function when the DOM is ready
html · try it yourself
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif">
  <ul id="list">
    <li>First</li>
    <li>Second</li>
  </ul>
  <button id="add">Add item</button>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    $(function () {
      const $list = $("#list");                         // select
      let count = $list.children().length;

      $("#add").on("click", function () {
        count++;
        const $item = $("<li>").text("Item " + count); // create
        $list.append($item);                           // insert
        $(this).text("Add item (" + count + ")");      // wrap `this`
        console.log("items:", $("li", $list).length);  // context search
      });
    });
  </script>
</body>
</html>

jQuery objects vs DOM elements

$() returns a jQuery object, not a DOM element. jQuery methods only work on jQuery objects, and DOM properties only work on DOM elements:

You have Works Does not work
$("#title") (jQuery object) .text(), .css(), .hide() .textContent, .style
document.getElementById("title") (element) .textContent, .style .text(), .hide()

Convert between them like this:

js
const $el = $("#title");
const el = $el[0];        // or $el.get(0) → the first DOM element
const $again = $(el);     // wrap a DOM element in jQuery

Tip: Many developers start variable names that hold jQuery objects with $ — $list, $button — so it is obvious which API they use.

html · try it yourself
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif">
  <h2 id="title">Hello</h2>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    const $title = $("#title");
    console.log("jQuery length:", $title.length);
    console.log("jQuery text():", $title.text());

    const el = $title[0];
    console.log("DOM tagName:", el.tagName);
    console.log("DOM textContent:", el.textContent);

    // a selector that matches nothing is NOT an error — just an empty set
    const $missing = $("#does-not-exist");
    console.log("missing length:", $missing.length);
    $missing.hide(); // silently does nothing
  </script>
</body>
</html>

Getters and setters

Many jQuery methods are both a getter and a setter, depending on whether you pass a value:

js
$("#name").text();          // getter: returns the text
$("#name").text("Ana");     // setter: changes it, returns the jQuery object

A getter reads from the first matched element only. A setter writes to all of them. Because setters return the jQuery object, you can chain calls — $("#box").addClass("on").text("On") — which you will practise in the Chaining lesson.

Test yourself

Which is the recommended way to run code when the DOM is ready in jQuery 3?

  1. $(document).on("ready", fn)
  2. $(fn)
  3. $.ready = fn
  4. window.ready(fn)

What does $("<p>Hi</p>") do?

  1. Selects all paragraphs containing Hi
  2. Creates a new <p> element (not yet in the page)
  3. Throws a syntax error
  4. Replaces the body with a paragraph

How do you get the plain DOM element from const $btn = $("#save")?

  1. $btn.element
  2. $btn[0]
  3. $btn.dom()
  4. $("#save").node