Skip to content

Instantly share code, notes, and snippets.

@roman0x58
Created September 2, 2017 06:44
Show Gist options
  • Save roman0x58/76e5799da8ea15dfc207adfc5e14c473 to your computer and use it in GitHub Desktop.
Save roman0x58/76e5799da8ea15dfc207adfc5e14c473 to your computer and use it in GitHub Desktop.
DOM TS
export class supports {
static classList(): boolean {
return 'classList' in document.documentElement
}
}
export class cls {
static has(el: HTMLElement, className: string): boolean {
if (supports.classList()) {
return el.classList.contains(className)
} else {
return cls.classReg(className).test(el.className)
}
}
static add(el: HTMLElement, className: string): HTMLElement {
if (supports.classList()) {
el.classList.add(className)
} else {
if (!cls.has(el, className)) {
el.className = `${el.className} ${className}`
}
}
return el;
}
static del(el: HTMLElement, className: string): HTMLElement {
if (supports.classList()) {
el.classList.remove(className)
} else {
el.className = el.className.replace(cls.classReg(className), ' ')
}
return el;
}
static toggle(el: HTMLElement, className: string): HTMLElement {
let fn = cls.has(el, className) ? cls.del : cls.add;
fn(el, className);
return el;
}
private static classReg(className: string): RegExp {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)")
}
static mod(el: HTMLElement, mod: string) {
let className = el.className.split(" ").pop();
return cls.add(el, `${className}--${mod}`);
}
}
export class dom {
static parent(el: HTMLElement, className: string): HTMLElement {
while (el) {
if (cls.has(el, className)) {
return el;
}
el = el.parentElement;
}
}
static ready(fn: () => any) {
document.addEventListener("DOMContentLoaded", fn);
}
static on(el: HTMLElement, event: string, f: (e: Event) => any): HTMLElement {
el.addEventListener(event, f, false);
return el;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment