Get element’s CSS selector (when it doesn’t have an id)

function fullPath(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(" > ");
}

console.log(  fullPath( $('input')[0] ) );
// "#search > DIV:nth-child(1) > INPUT:nth-child(1)"

This seems to be what you are asking for, but you may realize that this is not guaranteed to uniquely identify only one element. (For the above example, all the sibling inputs would be matched as well.)

Edit: Changed code to use nth-child instead of CSS classes to properly disambiguate for a single child.

Leave a Comment