Skip to content
jQuery

Method Chaining

Chain jQuery methods and use end() to restore context.

By EZ4Code Team
chainingfluent-api

Code

// Most methods return the jQuery object, enabling chains
$("#box")
  .addClass("highlight")
  .css({ color: "red", "font-weight": "bold" })
  .slideDown(300)
  .find("span")
    .text("Updated")
    .end()
  .attr("data-status", "ready");

// end() pops the most recent filtering/traversal step
$("ul")
  .find("li")
    .addClass("item")
    .end()
  .addClass("list");

Explanation

Chaining works because most jQuery methods return the same jQuery object. Methods like find() create a new context, and end() restores the previous one to continue chaining. This produces concise, expressive code without intermediate variables.

More jQuery Snippets