The jQuery each() Method: Iterate Over HTML Elements

Applying code to selected HTML elements one at a time calls for a way to handle each match. jQuery’s each() method does that by calling a function for each element in a selection.

I’ll show how to use each() and distinguish the jQuery collection from the current element inside a plugin callback.

TL;DR

In a jQuery plugin, outer this is the selected collection. The expression this.each() runs a callback over its elements. Inside that callback, a regular function receives the current DOM node as this.

  • Call $(selector).each() on a jQuery selection of DOM elements.
  • Call $.each() with an array, array-like value, or object.
  • Return exactly false from a jQuery callback to stop that iteration.

What Is jQuery each()?

jQuery has a collection method called each() and a utility function called $.each(). Both invoke a callback repeatedly, but the input and callback behavior depend on which form is used. The expression this.each() is used inside plugin code that extends jQuery’s collection methods.

In a method added to $.fn, the outer this is the jQuery collection. Returning this.each(function () { … }) applies per-element work and returns the collection iteration result for chaining, as shown in the plugin-authoring guide.

A plugin may use the callback to read an attribute, calculate an element-specific value, or attach per-node data. The example later uses a data attribute so the effect can be checked independently for each item.

FormInputCallback valuesTypical use
$(selector).each(callback)jQuery collection of DOM nodesIndex and element, with this set to the elementElement-specific DOM logic
$.each(value, callback)Array, array-like value, or objectIndex or key, followed by valueData entries or object properties

When the same change applies to every selected element, many jQuery methods already perform implicit iteration. For example, addClass() applies to the whole collection without a separate callback. The jQuery each() documentation recommends this approach when one collection method handles the task.

For a native JavaScript array, Array.prototype.forEach() is another option. Its callback receives the value before the index. When a loop needs native break or continue statements, use a for loop instead of expecting a jQuery callback return value to behave like those statements.

How to Use jQuery each() Step by Step

Work through the collection and callback as separate scopes. First decide what the outer function receives. Then examine the arguments and context supplied when the callback runs.

Step 1: Select the intended elements

Start with a selector that matches the nodes the task needs. A broad selector such as $(“li”) might include list items in unrelated parts of a page. A narrower selector such as $(“.cart-item”) describes the intended group more directly.

A selection records the matches found when the selector runs. If code runs before the target markup exists, or the selector uses a class that the markup does not have, the selection can be empty. In my run, $(“li.missing”) produced zero callback calls, which I verified with a counter.

For browser code, place the script after the relevant markup or wait for the document-ready event. The jQuery ready reference explains that timing option.

Step 2: Read the callback values

The collection callback receives the zero-based index followed by the raw DOM element. Use the element directly for browser properties such as textContent, or wrap it as $(element) before calling a jQuery method such as text(). With a regular callback, this is that same DOM node.

Name the arguments when the callback uses them, for example function (index, element). An arrow callback retains this from the surrounding scope, so pass the element argument when an arrow function fits the code.

Step 3: Run a complete example

The file below creates a small DOM with jsdom and sets its window and document before requiring jQuery. It checks collection iteration, an empty selector, an early exit in $.each(), and a plugin method that returns this.each(). The run used jQuery 4.0.0 and jsdom 31.0.1.

Save the source as jquery_each_demo.js, install jquery and jsdom with npm install jquery jsdom, then run node jquery_each_demo.js. I ran that command from the named source file. Requiring jQuery before a window existed returned “jQuery requires a window with a document.”

Creating jsdom and assigning window and document before requiring jQuery resolved that setup error. The source file uses the same setup so the callback behavior can run in Node.

const { JSDOM } = require("jsdom");

const dom = new JSDOM("<!doctype html><ul><li>alpha</li><li>beta</li><li>gamma</li></ul>");
global.window = dom.window;
global.document = dom.window.document;
const $ = require("jquery");

$("li").each(function (index, element) {
  console.log(`${index}: ${$(element).text()}; this matches: ${this === element}`);
});

let visited = 0;
$("li.missing").each(function () {
  visited += 1;
});
console.log(`empty selection callbacks: ${visited}`);

const values = ["red", "green", "blue"];
const seen = [];
$.each(values, function (index, value) {
  seen.push(`${index}=${value}`);
  if (value === "green") return false;
});
console.log(`$.each stopped after: ${seen.join(", ")}`);

$.fn.markItems = function () {
  return this.each(function () {
    $(this).attr("data-visited", "yes");
  });
};
const marked = $("li").markItems().addClass("processed");
console.log(`plugin chain retained elements: ${marked.length}`);
console.log(`plugin marked each: ${$("li[data-visited='yes']").length}`);

dom.window.close();

The output prints each callback index and confirms that this matches the element argument. The empty selector produces a count of zero, and the data loop stops at green. The plugin call then returns a collection that supports the chained class update, and every selected item receives the data attribute.

0: alpha; this matches: true
1: beta; this matches: true
2: gamma; this matches: true
empty selection callbacks: 0
$.each stopped after: 0=red, 1=green
plugin chain retained elements: 3
plugin marked each: 3
Terminal output showing jQuery each callbacks, early stop, and a chainable plugin

Edge Cases and Next Steps

Several nearby situations can change the best next action. The table maps each case to a check and a response rather than repeating the example above.

SituationWhat to checkResponse
The DOM changes after selectionWas the element inserted after the selector ran?Run a new selection for another pass, or delegate future events to an existing parent with .on().
A single setter should affect every matchDoes the jQuery method operate on the collection?Call a method such as $(“li”).addClass(“seen”) directly.
A data object contains length and numbered keysCould jQuery treat its shape as array-like?Inspect the input before iteration. The behavior is discussed in jQuery issue 4874.
A native array is the only inputDoes the operation need jQuery?Consider forEach() for value-first callbacks, or a for loop for direct break and continue.
A plugin must remain chainableDoes its method return the collection?Return the result of this.each(…) as shown in the plugin-authoring example.

For later-added descendants, event delegation addresses a different need from another pass over a selection. Attach a handler to a parent already on the page and provide the descendant selector. The jQuery .on() reference describes how bubbling events from matching descendants reach that parent.

An object with numeric length and indexed properties may take jQuery’s array-like path instead of property-by-property iteration. The utility API documentation describes array-like inputs, and issue 4874 discusses this case.

Return exactly false from the callback to stop the current jQuery iteration. Returning another value does not request that stop.

Statements after the each() call still run. To leave the surrounding function too, test a flag or return from that function separately.

Conclusion

Read a plugin method and its each callback as separate scopes. That distinction identifies the object at each scope. The executed example checks the per-item effect and the returned chain.

For more background, read CodeForGeek’s introduction to jQuery and its guide to jQuery load, get, and post methods. The jQuery plugin-authoring guide covers the same collection-return convention.

FAQ

These answers focus on the nested plugin and callback scopes.

What does this refer to in this.each()?

In a plugin method, outer this is the jQuery collection. Inside the regular function passed to this.each(), this is the current raw DOM element.

How do I stop a jQuery each() loop?

Return exactly false from the callback to stop the current jQuery iteration. Code after the call continues unless the surrounding function returns separately.

What is the difference between $(selector).each() and $.each()?

$(selector).each() visits matched DOM nodes. $.each() visits arrays, array-like values, or object properties.

Adarshita Gupta
Adarshita Gupta

Adarshita Gupta writes about JavaScript and jQuery troubleshooting alongside blockchain and crypto concepts. Her work covers npm and Node.js fixes, Ethereum, tokenomics, decentralized exchanges, and blockchain use cases.

Articles: 30