All questions

DOM Method Chaining

Premium

DOM Method Chaining

jQuery's signature move is the chain: $('.card').addClass('open').text('Hi').attr('role', 'dialog') reads like a sentence and touches every matched element. The trick behind it is almost embarrassingly small — every mutating method just returns the wrapper (this) instead of undefined, so the next call has something to run on. This "fluent interface" pattern shows up far beyond the DOM (query builders, test assertions, streams), and building a mini jQuery is the clearest way to internalise it.

Implement domMethodChaining(target, root) returning a wrapper over a set of elements with chainable methods.

Signature

function domMethodChaining(target, root = document) {
  return wrapper; // { addClass, text, attr, css, on, each, length, ... }
}

Examples

const $ = domMethodChaining;

$(node).addClass('box').text('hello').attr('id', 'x'); // all applied, in order
$('.item', container).addClass('on');                  // applies to EVERY match
$(node).text();                                         // no arg -> getter, returns text

Notes

  • Wrap a settarget is a selector (queried in root), a single Node, or a NodeList. Methods act on all wrapped elements.
  • Setters return the wrapper — that single decision (return this) is what makes calls chain.
  • Getters end the chain — calling text()/attr(name)/html()/css(prop) with no value returns the value from the first element instead of the wrapper.
  • Be empty-safe — a selector that matches nothing yields a length-0 wrapper whose setters no-op and whose getters return undefined.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium