Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 56 Β· Getting Started

The jQuery Object

Understand what $() returns: a jQuery collection, not a DOM node. Learn length, indexing, .get(), .eq(), implicit iteration, chaining and getter vs setter results.

When you write $("p"), you do not get a paragraph. You get a jQuery object: a special wrapper around zero, one or many DOM elements. Almost every jQuery bug a beginner meets comes from confusing the wrapper with the thing inside it, so this lesson is worth reading slowly.

You will learn how to look inside a jQuery object, how to move between the wrapper and plain DOM nodes, why one method call can affect many elements, what chaining is and why getters and setters return different things.

A collection that looks like an array

A jQuery object holds the matched elements in numbered slots and exposes a length, just like an array. It is array-like, but it is not a real array: it has no .map() that returns a plain array, no .push() in everyday use and so on, only jQuery's own methods.

Peek inside a jQuery object

Important points from the output:

  • .length tells you how many elements matched. A selector that matches nothing is not an error: it gives an object with length 0, and every method on it silently does nothing.
  • $fruit[0] is the raw DOM element, the same thing document.querySelector would return. You can read .textContent or call .classList.add() on it.
  • It is not an array, so Array.isArray returns false.

A tidy convention, used throughout this tutorial, is to start the names of variables holding jQuery objects with a dollar sign: $fruit, $items. It reminds the reader that the variable holds a wrapper, not a node.

Checking .length is the standard way to ask "did my selector find anything?": if ($(".error").length) { ... }. A jQuery object is always truthy, even when empty, so if ($(".error")) is a mistake that is always true.

From the wrapper to the DOM, and back

You will often need to cross between the two worlds.

From jQuery to DOM nodes:

Expression Returns
$items[0] the first raw DOM element
$items.get(1) the element at index 1 (same as $items[1])
$items.get() a real array of all the DOM elements
$items.eq(1) a jQuery object containing only the element at index 1

The difference between .get(n) and .eq(n) is the one to remember: get gives you the plain node, eq gives you a new wrapper, so you can keep calling jQuery methods. Negative numbers count from the end for both: .eq(-1) is the last one.

From a DOM node to jQuery: wrap it with $():

JavaScript
var button = document.getElementById("save");   // plain DOM node
$(button).addClass("busy");                      // now we can use jQuery methods

Inside event handlers you will see $(this) constantly. this is the raw DOM element that triggered the event, and $(this) wraps it. This is the bridge you will cross every day, for example when mixing in a native API that jQuery does not wrap.

get() versus eq()

Implicit iteration

Here is where the wrapper pays off. When a method acts on a collection, jQuery applies it to every element in it. You do not write the loop:

JavaScript
$("li").addClass("picked");   // adds the class to all list items
$("li").hide();               // hides all of them

This is implicit iteration. A plain DOM equivalent needs querySelectorAll plus a forEach. It works the same with one element or a hundred, and also with none, where it does nothing and throws nothing.

Setters apply to every matched element. Getters are different: they read from the first element only (with .text() as an exception that combines the text of all of them). Keep that asymmetry in mind: $("li").attr("id") returns the id of the first list item, not a list of ids. When you truly need a value from each element, you loop yourself with .each() or .map(), covered in Working with Collections.

Chaining

Most jQuery methods that change something return the same jQuery object they were called on. This lets you chain calls, one after another, on a single selection:

JavaScript
$("#message")
  .text("Saved!")
  .addClass("success")
  .fadeIn(200);

The selection happens once, and then three actions run on it in order. Writing each call on its own indented line, with the dot at the start, keeps long chains readable. Chaining is faster than repeating $("#message") three times, because each $() call searches the page again.

What a method returns depends on how you call it:

Call Role Returns
$("#a").text("Hi") setter the jQuery object (so you can chain)
$("#a").text() getter the string (chaining ends here)
$("p").first() traversal a new jQuery object
$("#a").hide() action the jQuery object

A getter hands you a plain value, so it must be the last link of a chain. If you try $("#a").text().addClass("x"), JavaScript tells you a string has no addClass.

Setters chain, getters end the chain

Inspecting objects in the console

When something does not work, look at what you actually have. Log the jQuery object to the browser console and expand it: you will see the matched elements under numbered keys, plus length and a prevObject that jQuery uses to remember where a traversal came from. Browsers print the matched DOM nodes, so you can hover over them to highlight each one on the page.

For quick checks, these are the most useful questions:

  • $("selector").length: how many matched?
  • $("selector")[0]: what is the first node?
  • $("selector").get(): show me all nodes as a real array.
  • $.fn.jquery: which jQuery version is running?

Wrapper or node?

jQuery object Has length, .eq(), .addClass(), .on().
DOM node Has .textContent, .classList, .addEventListener().
Unwrap Use [0] or .get(n).
Wrap Use $(node).

Know which one you are holding before you call a method.

1 / 2

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does $(".missing") return when no element has the class "missing"?

    jQuery always returns a jQuery object. When nothing matched, length is 0 and methods called on it do nothing.
  2. 2. What is the difference between .get(1) and .eq(1)?

    .get() unwraps to the DOM node. .eq() keeps a jQuery object so you can continue calling jQuery methods.
  3. 3. Why does $("#box").text().addClass("on") fail?

    Setters return the jQuery object, which allows chaining. A getter returns a plain value, so the chain ends there.
  4. 4. What is the right way to test whether $(".error") found anything?

    A jQuery object is always truthy, even when empty. Check its length instead.
  5. 5. What does $("li").attr("id") return for a list of five items?

    Getters read from the first matched element. Use .each() or .map() to read a value from every element.

Summary

  • $() returns a jQuery object: an array-like wrapper with a length, even when nothing matched.
  • Use [n] or .get(n) to reach a DOM node, .eq(n) to stay inside jQuery, and $(node) to wrap a node.
  • Methods apply to every element in the collection (implicit iteration); getters read from the first one.
  • Setters return the jQuery object, so calls can be chained; getters return plain values and end the chain.
  • Check .length to find out whether a selection matched; log the object to the console when in doubt.

Next, let's learn how to build selections in Basic Selectors.