Created
April 30, 2024 03:11
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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