A JavaScript reverse CSS selector

In plain Javascript, you can get a reference to a particular HTML element by using the querySelector method. For example:


Will give you a reference to the first “div” that’s encountered in the page. Give it a try in DevTools

Sample querySelector

What if we want to do the reverse? That is, given an element, get the correct query selector. In essence this is what Chrome DevTools does when you right click on an element and “Copy Selector”

Getting the Selector given an element

Seems to me that we can go through the process of writing our own function and testing all the edge cases – but if Chrome does it, maybe we could reverse engineer the code and use that…

The code we’re interested in resides here, in the open source fork of Chrome (Chromium):


After an hour or so of figuring out which parts we need, and which parts we broke, we end up with the code attached to the end of this article. Let’s test…. first a quick “click” listener which prints out the results whenever we click an HTML element:

document.addEventListener('click', function(e) { 
Test screencast

As I click randomly in the page on the left, note how the selectors appear in the console window on the bottom right