- Published on
BigFrontEnd Category 9 jQuery Implementation Questions
- Authors
- Name
- Yinhuan Yuan
Introduction
This blog post summarizes the jQuery implementation related questions found on BigFrontEnd.Dev.
1.implement a simple DOM wrapper to support method chaining like jQuery
15.https://bigfrontend.dev/problem/implement-a-simple-DOM-wrapper-to-support-method-chaining-like-jQuery I believe you've used jQuery before, we often chain the jQuery methods together to accomplish our goals.
For example, below chained call turns button into a black button with white text.
$("#button")
.css("color", "#fff")
.css("backgroundColor", "#000")
.css("fontWeight", "bold");
The chaining makes the code simple to read, could you create a simple wrapper $ to make above code work as expected?
The wrapper only needs to have css(propertyName: string, value: any)
/**
* @param {HTMLElement} el - element to be wrapped
*/
class Wrapper {
constructor(element) {
this.element = element;
}
css(propertyName, value) {
this.element.style[propertyName] = value;
return this; // Enable chaining by returning the instance
}
}
function $(el) {
return new Wrapper(el);
}
/**
* @param {HTMLElement} el - element to be wrapped
*/
function $(el) {
const css = (name, value) => {
el.style[name] = value;
return { css };
};
return {
css,
};
}