This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
15. implement a simple DOM wrapper to support method chaining like jQuery
Sure, here's an implementation of the $
wrapper that supports chaining:
const $ = function(selector) {
const elements = document.querySelectorAll(selector);
// helper function to apply style to all elements
const applyStyle = function(propertyName, value) {
elements.forEach((element) => {
element.style[propertyName] = value;
});
return this; // return this to enable chaining
}
return {
css: applyStyle // expose the applyStyle function as css method
};
};
// usage:
$('#button')
.css('color', '#fff')
.css('backgroundColor', '#000')
.css('fontWeight', 'bold');
What this does is create a function $
that takes a CSS selector as input and returns an object with a single css
method. The css
method takes two arguments, a propertyName
and a value
, and sets that style for all elements matching the selector using the applyStyle
helper function.
Importantly, applyStyle
returns this
, allowing the methods to be chained together. In this implementation, each call to $
creates a new object with its own applyStyle
function, effectively isolating the chained calls from each other.
Hope that helps!