Code snippets: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
m (→‎XPath helper: remove example that won't work (prototype.js based code?))
m (Redirected page to Category:Coding Tips)
 
(153 intermediate revisions by 40 users not shown)
Line 1: Line 1:
__TOC__
#REDIRECT [[:Category:Coding Tips]]
 
= Shortcut to document.getElementById =
 
function $(id) {
  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;
}
 
= Serialize/deserialize for GM_getValue =
 
Used to store and retrieve multiple values (typically as a serialized hash) in a single [[GM_getValue]] slot.
 
function deserialize(name, def) {
  return eval(GM_getValue(name, (def || '({})')));
}
function serialize(name, val) {
  GM_setValue(name, uneval(val));
}
 
Example usage:
 
var settings = {a: 1, b: 2, c: 3};
serialize('test', settings);
var _settings = deserialize('test');
// now "settings == _settings" should be true
 
= DOM node juggling =
 
== Remove DOM node ==
 
function remove(element) {
  if (element)
    element.parentNode.removeChild(element);
}
 
== Insert node after node ==
 
function insertAfter(newNode, node) {
  var parent = node.parentNode;
  return node.nextSibling ? parent.insertBefore(newNode, node.nextSibling) : parent.appendChild(newNode);
}
 
Example usage:
 
var link = document.getElementById("the_link");
var icon = document.createElement("img");
icon.src = "…";
insertAfter(icon, link);
 
= GET an URL with callback function =
 
Retrieves <code>url</code> using HTTP GET, then calls the function <code>cb</code> with the response text as its single argument.
 
function get(url, cb) {
  GM_xmlhttpRequest({
    method: "GET",
      url: url,
      onload: function(xhr) { cb(xhr.responseText); }
  });
}
 
Example usage:
 
function inform(text) {
  alert("The HTML of the page: " + text);
}
 
get("http://www.google.com", inform);

Latest revision as of 19:09, 4 February 2010