Code snippets
From GreaseSpot Wiki
Shortcut to document.getElementById
function $(id) { return document.getElementById(id); }
Example usage:
$("header").innerHTML = "Halloa!";
XPath helper
Run a particular XPath expression p
against the context node context
(or the document, if not provided).
Returns the results as an array.
function $x(p, context) { if (!context) context = document; var i, arr = [], xpr = document.evaluate(p, context, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); for (i = 0; item = xpr.snapshotItem(i); i ) arr.push(item); return arr; }
Example usage (with Array.forEach):
var paragraphs = $x("//p"); paragraphs.forEach(function(paragraph) { // Loop over every paragraph paragraph.innerHTML = "Halloa!"; });
Note: When you specify a context node, you need to use a relative XPath expression.
Get elements by CSS selector
Lets you run an XPath using the concise CSS style selectors such as .class and #id, it also adds a much needed method of comparing the ends of strings, $=.
function $$(xpath,root) { xpath=xpath.replace(/((^|\|)\s*)([^/|\s] )/g,'$2.//$3'). replace(/\.([\w-] )(?!([^\]]*]))/g,'[@class="$1" or @class$=" $1" or @class^="$1 " or @class~=" $1 "]'). replace(/#([\w-] )/g,'[@id="$1"]'). replace(/\/\[/g,'/*['); str='(@\\w |"[^"]*"|\'[^\']*\')' xpath=xpath.replace(new RegExp(str '\\s*~=\\s*' str,'g'),'contains($1,$2)'). replace(new RegExp(str '\\s*\\^=\\s*' str,'g'),'starts-with($1,$2)'). replace(new RegExp(str '\\s*\\$=\\s*' str,'g'),'substring($1,string-length($1)-string-length($2) 1)=$2'); var got=document.evaluate(xpath,root||document,null,null,null), result=[]; while(next=got.iterateNext()) result.push(next); return result; }
Example usage:
$$('#title')[0].innerHTML='Greased'; $$('a[@href $= "user.js"]').forEach(function (a) { a.innerHTML='check it out a script'; } $$('a[@href ^= "http"]').forEach(function (a) { a.innerHTML = ' (external)'; }
Conditional logging
Used to easily toggle sending debug messages to the console. Passes all arguments on to console.log, but only if console
is defined (for backward compatibility) and DEBUG
is true
.
Code and example usage:
const DEBUG = true; var links = document.links; debug("Links: %o", links); function debug() { if (DEBUG