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.
function domMethodChaining(target, root = document) {
return wrapper; // { addClass, text, attr, css, on, each, length, ... }
}
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
target is a selector (queried in root), a single Node, or a NodeList. Methods act on all wrapped elements.return this) is what makes calls chain.text()/attr(name)/html()/css(prop) with no value returns the value from the first element instead of the wrapper.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.