Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, let's stick to a narrow class of selectors involving tag names, class names and IDs, nothing fancy like <code>E &gt; F</code> or <code>E + F</code>. Let's also disallow combinations of class names (<code>.class1.class2.class3</code>), otherwise a single element with 10 class names would generate 4 million selectors alone.</p> <p>Each of our full selectors consists of simple selectors separated by spaces. Every simple selector is a combination of <code>tag{0,1}id{0,1}class{0,n}</code> - i.e. each element has exactly one tag, at most one ID, and it can have an arbitrary number of class names. That gives us the upper limit of 2 * 2 * (n + 1) simple selectors for a single element.</p> <p>Given a reference to a DOM element grab it's tag name, ID and class names. Calculate all possible simple selectors as described above. Lets call this set A1. Move one step up the hierarchy to it's parent, calculate all simple selectors for that parent element - that'll be the set A2. Continue until you reach the html element - the set Am. Now you'll have a list, consisting of m items, each item is a set of simple selectors.</p> <p>Now pick some of these sets and find their cartesian product. Say, m = 5. How many sets can you pick? The set A1 is always present, but others are optional. For each one of them you either pick it or not. That's like binary numbers:</p> <pre><code>0000 // 0, A1 0001 // 1, A1 x A2 0010 // 2, A1 x A3 0011 // 3, A1 x A2 x A3 0100 // 4, A1 x A4 ... </code></pre> <p>That means you'll have 2^(m-1) cartesian products. You can now convert them to strings. The last step is to remove duplicates, consider this example:</p> <pre><code>&lt;div&gt; &lt;div&gt; &lt;span&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Our calculations will yield this list:</p> <pre><code> span div span // inner div div span // outer div div div span </code></pre> <p>Those two divs yield duplicate selectors. Remove those and the job is done. All the steps are very simple algorithmically. I'm sure you can figure them out, but if you get stuck somewhere or need further clarification feel free to ask me in the comments.</p> <hr> <p><strong>UPDATE</strong></p> <p>So, I decided to play with it a bit more and wrote the program, here's the list of selectors your example generates: <a href="http://pastie.org/1616164" rel="nofollow">http://pastie.org/1616164</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload