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 NodeList
s 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 map
ing 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
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. ↩
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. ↩