Skip to content

Instantly share code, notes, and snippets.

@stevoland
Created September 13, 2012 11:11
Show Gist options
  • Save stevoland/3713624 to your computer and use it in GitHub Desktop.
Save stevoland/3713624 to your computer and use it in GitHub Desktop.

Revisions

  1. stevoland created this gist Sep 13, 2012.
    18 changes: 18 additions & 0 deletions getCSSSelector.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    function getCSSSelector(el) {
    var names = [];
    while (el.parentNode) {
    if (el.id) {
    names.unshift('#' + el.id);
    break;
    } else {
    if (el == el.ownerDocument.documentElement) {
    names.unshift(el.tagName);
    } else {
    for (var c=1, e=el; e.previousElementSibling; e=e.previousElementSibling, c++);
    names.unshift(el.tagName + ':nth-child(' + c + ')');
    }
    el = el.parentNode;
    }
    }
    return names.join(' > ');
    }