Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Last active Aug 29, 2015
Embed
What would you like to do?
core
export function $(value) {
if(value == null) {
return []
}
if(typeof value === "string") {
return [...document.querySelectorAll(value)]
}
if(typeof value.nodeType === "number") {
return Array.of(value)
}
if(typeof value.length === "number") {
return [...value]
}
}
export function on(type, listener, capture) {
this.forEach((element) => {
element.addEventListener(type, listener, capture)
})
return this
}
export function off(type, listener, capture) {
this.forEach((element) => {
element.removeEventListener(type, listener, capture)
})
return this
}
export function addClass(...classNames) {
this.forEach((element) => {
element.classList.add(...classNames)
})
}
export function removeClass(...classNames) {
this.forEach((element) => {
element.classList.remove(...classNames)
})
return this
}
export function toggleClass(...classNames) {
this.forEach((element) => {
element.classList.toggle(...classNames)
})
return this
}
export function hasClass(...classNames) {
for(const element of this) {
return element.classList.contains(...classNames)
}
}
export function getStyle(propertyName) {
for(const element of this) {
return getComputedStyle(element, null)[propertyName]
}
}
export function setStyle(object) {
this.forEach((element) => {
for(let key in object) {
element.style[key] = object[key]
}
})
return this
}
export function getAttribute(attributeName) {
for(const element of this) {
return element.getAttribute(attributeName)
}
}
export function setAttribute(attributeName, value) {
this.forEach((element) => {
element.setAttribute(attributeName, value)
})
return this
}
export function hasAttribute(attributeName) {
for(const element of this) {
return element.hasAttribute(attributeName)
}
}
export function append(node) {
for(const element of this) {
if(!Array.isArray(node)) {
node = [node]
}
const fragment = document.createDocumentFragment()
node.forEach((node) => fragment.appendChild(node))
element.appendChild(fragment)
}
}
import {$, addEventListener, getStyle, setStyle} from "./core"
const node = $(document.createElement("div"))
$(document.body)
::append(node)
node
::setStyle({
"height": "100px",
"width": "100px",
"background-color": "#c30",
})
::on("click", () => {
node
::setStyle({
height: `${ parseInt(node::getStyle("height"), 10) + 100 }px`
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment