Skip to content

Instantly share code, notes, and snippets.

@amitasaurus
Created April 30, 2024 03:11
Show Gist options
  • Save amitasaurus/ca369603518d4997a9f2c400f2758dc7 to your computer and use it in GitHub Desktop.
Save amitasaurus/ca369603518d4997a9f2c400f2758dc7 to your computer and use it in GitHub Desktop.
Implement the jQuery single-character function $ which only needs to supports the css() method that either gets the value of a computed style property or sets a CSS property on the matched element.
import $ from './functions/jQuery.css';
document.body.innerHTML = '<button>Click me</button>';
$('button')
.css('color', 'red')
.css('backgroundColor', 'tomato')
.css('fontSize', '16px');
$('button').css('color');
interface JQuery {
css: (
prop: string,
value?: boolean | string | number
) => JQuery | string | undefined;
}
export default function $(selector: string): JQuery {
const element = document.querySelector(selector) as HTMLElement;
return {
css: function (prop: string, value?: boolean | string | number) {
if (value) {
if (element) (element?.style as any)[prop] = value;
return this;
} else {
const styleValue = element ? (element?.style as any)[prop] : '';
return styleValue.length > 0 ? styleValue : undefined;
}
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment