Code snippets: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
No edit summary
m (Redirected page to Category:Coding Tips)
 
(85 intermediate revisions by 23 users not shown)
Line 1: Line 1:
__TOC__
#REDIRECT [[:Category:Coding Tips]]
 
= Shortcut to document.getElementById =
 
function $(id) {
  return document.getElementById(id);
}
 
Example usage:
 
$("header").innerHTML = "Halloa!";
 
 
= XPath helper =
 
Run a particular [[XPath]] expression <code>p</code> against the context node <code>context</code> (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 [[Coding_tips#array.forEach|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 [[XPath#Relative_paths|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 <code>console</code> is defined (for backward compatibility) and <code>DEBUG</code> is <code>true</code>.
 
Code and example usage:
 
const DEBUG = true;
var links = document.links;
debug("Links: %o", links);
function debug() {
  if (DEBUG

Latest revision as of 19:09, 4 February 2010