Code snippets: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
No edit summary
(Use array.forEach instead of a for loop)
Line 27: Line 27:


  var i, paragraphs = $x("//p");
  var i, paragraphs = $x("//p");
  for (i = 0; i < paragraphs.length; i++) {  // Loop over every paragraph
  paragraphs.forEach(function(element) {  // Loop over every element
   paragraphs[i].innerHTML = "Halloa!";
   element.innerHTML = "Halloa!";
  }
  });


= Serialize/deserialize =
= Serialize/deserialize =

Revision as of 21:45, 23 March 2007

Shortcut to document.getElementById

function $(id) {
  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:

var i, paragraphs = $x("//p");
paragraphs.forEach(function(element) {  // Loop over every element
  element.innerHTML = "Halloa!";
});

Serialize/deserialize

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 ? 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

GET an URL with callback function

Retrieves url using HTTP GET, then calls the function cb 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);