http://stackoverflow.com/questions/4588119/get-elements-css-selector-when-it-doesnt-have-an-id
338831
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(" > ");
}
1343515
function $tag(tag, id, css) {
		var element = document.createElement(tag);

		if (id) {
			element.id = prefix + id;
		}

		if (css) {
			element.style.cssText = css;
		}

		return $(element);
    }
574929
function _getSelectorInFinalCSSForm(selectorArray) {
        var finalSelectorArray = [""],
            parentSelectorArray = [],
            group = [];
        _.forEach(selectorArray, function (selector) {
            selector = _stripAtRules(selector);
            group = selector.split(",");
            parentSelectorArray = [];
            _.forEach(group, function (cs) {
                var ampersandIndex = cs.indexOf("&");
                _.forEach(finalSelectorArray, function (ps) {
                    if (ampersandIndex === -1) {
                        cs = _stripAtRules(cs);
                        if (ps.length && cs.length) {
                            ps += " ";
                        }
                        ps += cs;
                    } else {
                        // Replace all instances of & with regexp
                        ps = _stripAtRules(cs.replace(/&/g, ps));
                    }
                    parentSelectorArray.push(ps);
                });
            });
            finalSelectorArray = parentSelectorArray;
        });
        return finalSelectorArray.join(", ");
    }
1215134
function selectorBlockHandler(element) {
    if (element.type === 'Selector') {
        const name = []
        let discard = false
        element.children.forEach(e => {
            switch (e.type) {
                case "ClassSelector":
                    name.push("." + e.name);
                    break;
                    //not support for now
                case "Combinator":
                    name.push(e.name);
                    discard = true
                    return null
                case "TypeSelector":
                    name.push(e.name);
                    break;
                case "IdSelector":
                    //not support for now
                    name.push("#" + e.name);
                    discard = true
                    return null
                case "WhiteSpace":
                    name.push(" ");
                    break
                default: {
                    // console.warn('unknown selector type:', e)
                    discard = true
                    return null
                }
            }
        })
        if (!discard)
            return name.join("")
        else return null
    }
}
476601
function () {

            var aOverlays = [],
                oElement = this.element;

            function compareZIndexDesc(p_oOverlay1, p_oOverlay2) {

                var sZIndex1 = Dom.getStyle(p_oOverlay1, "zIndex"),
                    sZIndex2 = Dom.getStyle(p_oOverlay2, "zIndex"),

                    nZIndex1 = (!sZIndex1 || isNaN(sZIndex1)) ? 0 : parseInt(sZIndex1, 10),
                    nZIndex2 = (!sZIndex2 || isNaN(sZIndex2)) ? 0 : parseInt(sZIndex2, 10);

                if (nZIndex1 > nZIndex2) {
                    return -1;
                } else if (nZIndex1 < nZIndex2) {
                    return 1;
                } else {
                    return 0;
                }
            }

            function isOverlayElement(p_oElement) {

                var isOverlay = Dom.hasClass(p_oElement, Overlay.CSS_OVERLAY),
                    Panel = YAHOO.widget.Panel;

                if (isOverlay && !Dom.isAncestor(oElement, p_oElement)) {
                    if (Panel && Dom.hasClass(p_oElement, Panel.CSS_PANEL)) {
                        aOverlays[aOverlays.length] = p_oElement.parentNode;
                    } else {
                        aOverlays[aOverlays.length] = p_oElement;
                    }
                }
            }

            Dom.getElementsBy(isOverlayElement, "DIV", document.body);

            aOverlays.sort(compareZIndexDesc);

            var oTopOverlay = aOverlays[0],
                nTopZIndex;

            if (oTopOverlay) {
                nTopZIndex = Dom.getStyle(oTopOverlay, "zIndex");

                if (!isNaN(nTopZIndex)) {
                    var bRequiresBump = false;

                    if (oTopOverlay != oElement) {
                        bRequiresBump = true;
                    } else if (aOverlays.length > 1) {
                        var nNextZIndex = Dom.getStyle(aOverlays[1], "zIndex");
                        // Don't rely on DOM order to stack if 2 overlays are at the same zindex.
                        if (!isNaN(nNextZIndex) && (nTopZIndex == nNextZIndex)) {
                            bRequiresBump = true;
                        }
                    }
                    if (bRequiresBump) {
                        this.cfg.setProperty("zindex", (parseInt(nTopZIndex, 10) + 2));
                    }
                }
            }
        }
90971
protected function getElements()
    {
        $name = str_replace('#', '', $this->selector);

        $id = str_replace(['[', ']'], ['\\[', '\\]'], $name);

        return collect(explode(',', $this->validElements()))->map(function ($element) use ($name, $id) {
            return "{$element}#{$id}, {$element}[name='{$name}']";
        })->all();
    }
251878
def find_elements(self, by=By.ID, value=None):
        
        if self._w3c:
            if by == By.ID:
                by = By.CSS_SELECTOR
                value = '[id="%s"]' % value
            elif by == By.TAG_NAME:
                by = By.CSS_SELECTOR
            elif by == By.CLASS_NAME:
                by = By.CSS_SELECTOR
                value = ".%s" % value
            elif by == By.NAME:
                by = By.CSS_SELECTOR
                value = '[name="%s"]' % value

        return self._execute(Command.FIND_CHILD_ELEMENTS,
                             {"using": by, "value": value})['value']
1081182
function ($el) {
      // Detect if completely empty.
      if (!$el || $el.length === 0) {
        return "<EMPTY OBJECT>";
      }

      var name = "";
      var id = $el.attr("id");
      var cls = $el.attr("class") || "";

      // Try CSS selector id.
      if (id) {
        name += "#" + id;
      }
      if (cls) {
        name += "." + cls.split(" ").join(".");
      }
      if (name) {
        return "'" + name + "'";
      }

      // Give up.
      return $el;
    }
1357325
private List<String> parseSelector() {
        List<String> selector = new ArrayList<>();
        parseSelectorPrefix(selector);

        while (tokenizer.more()) {
            if (tokenizer.current().isSymbol("{", ",")) {
                if (selector.isEmpty()) {
                    tokenizer.addError(tokenizer.current(), "Unexpected end of CSS selector");
                }

                return selector;
            } else if (tokenizer.current().isIdentifier()
                       || tokenizer.current().isSpecialIdentifier("#", "@")
                       || tokenizer.current().isNumber()) {
                StringBuilder sb = new StringBuilder(tokenizer.consume().getSource());
                parseFilterInSelector(sb);
                parseOperatorInSelector(sb);
                selector.add(sb.toString());
            } else if (tokenizer.current().isSymbol("&") || tokenizer.current().isSymbol("*")) {
                selector.add(tokenizer.consume().getTrigger());
            } else if (tokenizer.current().isSymbol(">", "+", "~")) {
                selector.add(tokenizer.consume().getSource());
            } else {
                tokenizer.addError(tokenizer.current(), "Unexpected Token: %s", tokenizer.consume().getSource());
            }
        }
        return selector;
    }
123851
final public function find($css_selector)
    {
        $find = NULL;

        $doc = new \PHPTools\PHPHtmlDom\PHPHtmlDom;

        if(!!$doc->importHTML($this->list_html))
        {
            $find = $doc->e($css_selector);
        }

        return $find;
    }
759198
def _element(cls):
        '''    '''
        if not cls.__is_selector():
            raise Exception("Invalid selector[%s]." %cls.__control["by"])
        
        driver = Web.driver
        try:            
            elements = WebDriverWait(driver, cls.__control["timeout"]).until(lambda driver: getattr(driver,"find_elements")(cls.__control["by"], cls.__control["value"]))
        except:                        
            raise Exception("Timeout at %d seconds.Element(%s) not found." %(cls.__control["timeout"],cls.__control["by"]))
        
        if len(elements) < cls.__control["index"] + 1:                    
            raise Exception("Element [%s]: Element Index Issue! There are [%s] Elements! Index=[%s]" % (cls.__name__, len(elements), cls.__control["index"]))
        
        if len(elements) > 1:              
            print("Element [%s]: There are [%d] elements, choosed index=%d" %(cls.__name__,len(elements),cls.__control["index"]))
        
        elm = elements[cls.__control["index"]]
        cls.__control["index"] = 0        
        return elm
690662
def span_with_id(span_id, options = {})
        if options && options[:index] then
          elements = find_elements(:id, span_id.to_s)
          elements[options[:index].to_i - 1].text
        else
          find_element(:id, span_id.to_s).text
        end
      end
1034789
function findElementInEvent(e, selector) {
            var el = $(e.target);
            if (!el.is(selector)) {
                if (typeof selector === 'string') {
                    el = el.parents(selector);
                }
                else if (selector.nodeType) {
                    var found;
                    el.parents().each(function (index, _el) {
                        if (_el === selector) found = selector;
                    });
                    if (!found) return undefined;
                    else return selector;
                }
            }
            if (el.length === 0) {
                return undefined;
            }
            return el[0];
        }
575340
def getElementById(self, _id):
        '''
            
        '''
        for tag in self:
            if tag.id == _id:
                return tag
            for subtag in tag.children:
                tmp = subtag.getElementById(_id)
                if tmp is not None:
                    return tmp
        return None
923691
function querySelector(selector) {
    init();
    if (!selector) {
      return tokens;
    }
    var match = selector.match(
      /^\s*([\w_-]*)((\s*\[[\w_-]+\s*=\s*("([^\\"]*(\\.)*)*"|'([^\\']*(\\.)*)*'|[^\[\]]*)\])*)\s*(\*?)$/
    );
    if (!match) {
      console.warn(colors.blue('Invalid selector expressions %j.'), selector);
      return;
    }
    var tag = match[1];
    var attributes = [];
    var all = match[9] === '*';
    match[2].replace(/\s*\[([\w_-]+)\s*=\s*("([^\\"]*(\\.)*)*"|'([^\\']*(\\.)*)*'|[^\[\]]*)\]/g,
      function (match, name, value) {
        if (/^['"]/.test(value)) {
          /*jslint evil: true */
          value = new Function('return (' + value + ');')();
        }
        attributes.push({
          name: name,
          value: value
        });
      }
    );
    function check(node) {
      if (!node || !node.attrs) {
        return;
      }
      var flag;
      if (!tag || node.tag === tag) {
        flag = true;
        attributes.every(function (item) {
          if (item.value !== node.attrs[item.name]) {
            flag = false;
          }
          return flag;
        });
      }
      return flag;
    }
    var items;
    function scan(node) {
      if (check(node)) {
        if (items) {
          items.push(node);
        }
        return node;
      }
      var result;
      if (node.nodes) {
        node.nodes.every(function (item) {
          result = scan(item);
          return items || !result;
        });
      }
      return result;
    }
    if (all) {
      items = [];
      scan(tokens);
      return items;
    }
    else {
      return scan(tokens);
    }
  }
146805
function getSelector(node)
{
	var name;
	var selector = [];
	
	while (node.nodeName !== "#document")
	{
		name = node.nodeName;
		
		// Only one of these are ever allowed -- so, index is unnecessary
		if (name!=="html" && name!=="body" & name!=="head")
		{
			name += ":nth-child("+ getNthIndex(node) +")";
		}
		
		// Building backwards
		selector.push(name);
		
		node = node.parentNode;
	}
	
	return selector.reverse().join(" > ");
}
1082356
function getId(element) {
        var state = getState(element);

        if (state && state.id !== undefined) {
            return state.id;
        }

        return null;
    }