About 15 minutes ago, I was working on a project and needed a list of the 50 states in the US. Not only that, I needed them in the form of an array of strings. Now sure, I could have just done the copy/paste routine from this site and done some tedious line-wise editing in Sublime, but instead, I decided to bust out my trusty hammer, Chrome Dev Tools1.

TL;DR:

Screen Thing

First, a cursory glance at the DOM reveals that the states are wrapped in a tags, which are all within a div with id="colwrap". Excellent. We can now craft a CSS selector that will return all of the nodes we need.

$$('#colwrap a')

No, that’s not a typo. Chrome Dev Tools aliases querySelectorAll to $$. We’re using standard DOM API’s, which means jQuery doesn’t need to be on the page.

Now, in the Dev Tools console, we see what looks like an array, but unfortunately, querySelectorAll actually returns a NodeList, which is an array-like object but doesn’t have Array.prototype’s methods. This is because the DOM API guys were jerks. This means we can’t use cool array methods like map or filter.

However, in rebellious fashion, we can take advantage of the fact that NodeLists look a lot like arrays (they’re “array-like objects”). Thus, we can use array methods on them with a little bit of JS black magic:

[].slice.call($$('#colwrap a'), 0)

We’ve basically converted the NodeList into an array with the ol’ .slice(0) array-copying trick.

Now it’s a matter of maping over the nodes and grabbing their innerText:

[].slice.call($$('#colwrap a'), 0).map(function(node) {
  return node.innerText;
})

At this point, we could copy and paste from the console to our trusty editor, but that requires lifting our hands from the keyboard to go for the mouse. Instead, we can use the Dev Tools copy function, which moves anything you pass it into the clipboard. So our final complete command is

copy([].slice.call($$('#colwrap a'), 0).map(function(node) {
  return node.innerText;
}))

Paste. Done!2

  1. This might seem like a contrived example, but I legitimately did this in order to get the list of 50 states formatted as an array of strings. Only then did I realize that this is a good demo of what you can do with Chrome Dev Tools.

  2. In practice, I don’t actually magically type out that last command off the top of my head. I usually build up to that by making judicious use of $_, which returns the result of the last executed command. See the TL;DR above.