Created
April 30, 2024 03:16
-
-
Save amitasaurus/54d0e7568835cd467c846770833ba248 to your computer and use it in GitHub Desktop.
jQuery (using the $ alias function), provided convenient APIs to toggle, add, and remove classes from elements via .toggleClass(), .addClass() and .removeClass().
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 { | |
toggleClass: (className: string, state?: boolean) => JQuery; | |
addClass: (className: string) => JQuery; | |
removeClass: (className: string) => JQuery; | |
} | |
export default function $(selector: string): JQuery { | |
const element = document.querySelector(selector); | |
return { | |
toggleClass: function (className: string, state?: boolean): JQuery { | |
if (state) return this; | |
const classNames = className.trim().split(' '); | |
classNames.forEach((_className) => { | |
if (_className.length > 0) { | |
element?.classList.contains(_className) | |
? this.removeClass(_className) | |
: this.addClass(_className); | |
} | |
}); | |
return this; | |
}, | |
addClass: function (className: string): JQuery { | |
element?.classList.add(className.trim()); | |
return this; | |
}, | |
removeClass: function (className): JQuery { | |
element?.classList.remove(className.trim()); | |
return this; | |
}, | |
}; | |
} |
Author
amitasaurus
commented
Apr 30, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment