views:

64

answers:

1

I wrote my first Greasemonkey user script to find logo requests on the college-football subreddit.

One wrinkle is having to search for the appropriate stylesheet, and then once found, I look through the selectorText attributes of documents.styleSheets[i].cssRules for known usernames.

At first, I used the following code to search for user comments

var missing = new Array();
var authors = document.evaluate(
                "//p[@class='tagline']/a[contains(@class, 'author')]",
                document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
                null);
for (var i = authors.snapshotLength - 1; i >= 0; i--) {
  var a = authors.snapshotItem(i);
  if (!hasLogo.hasOwnProperty(a.innerHTML)) {
    missing.push(a.innerHTML);
  }
}

but jQuery makes it so concise!

var missing = [];
$("p.tagline a.author").each(
  function (index) {
    var name = $(this).text();
    if (!hasLogo.hasOwnProperty(name))
      missing.push(name);
  });

Please suggest more improvements!

+1  A: 

You can use .map() to cut it down a bit, and .innerHTML instead of creating a new jQuery object to grab .text() on, given the specifics of how authors are on the page, like this:

var missing = $("p.tagline a.author").map(function() {
  var name = this.innerHTML;
  return !hasLogo.hasOwnProperty(name) && name;
}).get();
Nick Craver