Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 56 ยท Traversing the DOM

Working with Collections

Loop over jQuery collections with .each() and $.each, build arrays with .map() and .get(), combine sets with .add() and .addBack(), and unwind chains with .end().

A jQuery object is a collection: an array-like set of zero or more elements, as you saw in the jQuery object. Most methods act on the whole set at once through implicit iteration, so $("li").addClass("x") needs no loop. But sometimes each element needs its own treatment: a different number, a value read from its own attribute, a decision based on its neighbours. This lesson covers the tools for those cases.

You will learn how to loop with .each() and $.each(), how to build values with .map(), how to grow a collection with .add() and .addBack(), how .end() rewinds a chain, and how to ask where an element sits with .index().

Looping and transforming

.each() Run code for every element.
.map() Turn elements into values.
.get() Turn the result into a real array.
1 / 2

.each(): run code for every element

.each(callback) calls your function once per element. Inside, this is the DOM element (not a jQuery object), and the arguments are the index and the element.

JavaScript
$("li").each(function (index, element) {
  // this === element
  $(this).text((index + 1) + ". " + $(this).text());
});

Wrap this in $(this) when you want jQuery methods. Use this directly for plain DOM properties such as this.id or this.checked, which is shorter and faster.

.each() returns the original jQuery object, so you can keep chaining after it.

Stopping early

Return false from the callback to break out of the loop. Returning anything else, including true, just moves on to the next element (like continue). A plain return; also continues.

JavaScript
let firstEmpty = null;
$("input").each(function () {
  if (this.value === "") {
    firstEmpty = this;
    return false;          // stop looking
  }
});

break and continue statements do not work inside the callback, because it is a function and not a loop body.

Arrow functions and this

If you use an arrow function as the callback, this is not the element. Use the second parameter instead:

JavaScript
$("li").each((i, el) => { $(el).addClass("n" + i); });

$.each(): loop over anything

$.each(collection, callback) is a utility function that works on arrays, array-likes and plain objects. The callback receives (indexOrKey, value), which is the opposite order from native Array.forEach.

JavaScript
$.each(["a", "b", "c"], function (i, letter) { /* ... */ });
$.each({ x: 1, y: 2 }, function (key, value) { /* ... */ });

Here this is the value (wrapped as an object for primitives), and return false also breaks. For arrays in new code, native forEach or for...of is usually clearer, but $.each is the only one of these that handles objects and array-likes in one call.

.map() and .get(): build new values

.map(callback) calls your function for each element and collects the return values into a new jQuery object. Note the callback signature (index, element): that is the reverse of $.map()'s (value, index) for arrays.

JavaScript
const ids = $("li").map(function () { return this.id; });   // jQuery object of strings
const idArray = ids.get();                                  // real array

Call .get() (with no argument) to convert the result to a plain array, which you can join, sort or send to the server. .toArray() does the same thing. .get(2) returns the single DOM element at index 2 and .get(-1) the last one.

Returning null or undefined drops that item, and returning an array flattens it into the result, so one element can produce several values.

each, map and get on a price list

.add() and .addBack(): grow the set

.add() creates a new set that contains the current elements plus whatever you pass: a selector, elements, HTML or another jQuery object. The result is in document order and without duplicates.

JavaScript
$("h1").add("h2").add(".lead").addClass("heading-like");

Because .add() returns a new object, the original $("h1") is unchanged.

.addBack() adds the previous set in the chain to the current one. It saves you from running two selections when you want an element and its descendants:

JavaScript
$("#card").find("a").addBack().addClass("linked");   // #card and every a inside

(Older code uses .andSelf(), which was removed in jQuery 3.)

.end(): step back in a chain

Every traversal method that changes the set remembers the previous one. .end() pops back to it. This lets you travel down, act, return and continue, all in one chain:

JavaScript
$("#menu")
  .find("li").addClass("item")       // acts on the li elements
  .end()                             // back to #menu
  .addClass("ready");                // acts on #menu again

Use this sparingly. One or two .end() calls are tidy; a long staircase of them is harder to read than separate statements with cached variables, as advised in selector performance.

.index(): where is this element?

.index() returns a zero-based position, or -1 if the element is not found. It has three forms:

  • $(el).index() with no argument: the position among its siblings. This is how you learn which list item was clicked.
  • $("li").index(el): the position of the element el inside that collection.
  • $("li").index("li.active"): the position of the first element matching the selector inside that collection.
add, addBack, end and index

Common mistakes

  • Forgetting $(this). Inside .each(), this is a raw DOM node, so this.text() fails. Use $(this).text().
  • Mixing up callback arguments. .each and .map use (index, element); $.map on an array uses (value, index).
  • Expecting .map() to return an array. It returns a jQuery object. Add .get() when you need an array.
  • Using return false to "skip" an item. It stops the whole loop in .each(). Use a bare return to continue.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Inside $('li').each(function () { ... }), what is this?

    this is the DOM element; wrap it with $(this) to use jQuery methods. With an arrow function you would use the second argument instead.
  2. 2. How do you stop an .each() loop early?

    Returning false breaks. Any other return value continues. break is a syntax error inside the callback function.
  3. 3. What does $('li').map(function () { return this.id; }).get() return?

    .map() builds a jQuery object; .get() converts it into an ordinary array.
  4. 4. What is .addBack() for?

    After .find(), .addBack() includes the elements you searched from. It only changes the collection, not the page.
  5. 5. What does $(this).index() return for the third li in a list?

    Positions are zero-based, so the third item has index 2.

Summary

  • .each(function (i, el) {}) runs code per element with this as the DOM node; return false breaks, a bare return continues.
  • $.each() also loops over arrays and plain objects, with (key, value) arguments.
  • .map() returns a jQuery object of your return values (skipping null); add .get() or .toArray() for a real array.
  • .add() merges more elements into a new set; .addBack() re-includes the previous set.
  • .end() returns to the previous set in the chain; use it sparingly.
  • .index() gives the zero-based position among siblings or within a given collection, and -1 when not found.

Next: Getting and Setting Content begins the Manipulating the DOM chapter with .text(), .html() and .val().