Skip to content

Instantly share code, notes, and snippets.

@cxmeel
Last active October 14, 2023 14:58
Show Gist options
  • Save cxmeel/3d97614cd62f645dde967769981e502e to your computer and use it in GitHub Desktop.
Save cxmeel/3d97614cd62f645dde967769981e502e to your computer and use it in GitHub Desktop.
JavaScript Snippets

A collection of JavaScript snippets, mostly used in custom UserScripts. You can paste them into your code directly, or @require them using the GitHub raw link.

// equivalent to `const container = document.querySelector("div.container")`
const container = $("div.container")

// equivalent to `const link = container.querySelector("a.something[href]")
const link = $(container)("a.something[href]")
globalThis.$ = (arg0) => typeof(arg0) === "string" ? document.querySelector(arg0) : arg0.querySelector.bind(arg0)
Node.prototype.swapTag = function(tag = "div") {
const node = document.createElement(tag)
for (const attribute of Array.from(this.attributes)) {
node.setAttribute(attribute.name, attribute.value)
}
for (const child of Array.from(this.childNodes)) {
node.append(child)
}
this.replaceWith(node)
return node
}
Node.prototype.wrapWith = function(element = Node) {
this.parentElement.insertBefore(element, this)
element.append(this)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment