Get css selector and xpath of an element
For stack overflow question
by daphtdazz
HTML
<div class=myclass>
<div>
<p id=right-clickable>Right click me</p>
<p>Clicking me won't help</p>
</div>
</div>
JavaScript
(function() {
var CssSelectorGenerator, root,
indexOf = [].indexOf || function(item) {
for (var i = 0, l = this.length; i < l; i++) {
if (i in this && this[i] === item) return i;
}
return -1;
};
CssSelectorGenerator = (function() {
CssSelectorGenerator.prototype.default_options = {
selectors: ['id', 'class', 'tag', 'nthchild']
};
function CssSelectorGenerator(options) {
if (options == null) {
options = {};
}
this.options = {};
this.setOptions(this.default_options);
this.setOptions(options);
}
CssSelectorGenerator.prototype.setOptions = function(options) {
var key, results, val;
if (options == null) {
options = {};
}
results = [];
for (key in options) {
val = options[key];
if (this.default_options.hasOwnProperty(key)) {
results.push(this.options[key] = val);
} else {
results.push(void 0);
}
}
return results;
};
CssSelectorGenerator.prototype.isElement = function(element) {
return !!((element != null ? element.nodeType : void 0) === 1);
};
CssSelectorGenerator.prototype.getParents = function(element) {
var current_element, result;
result = [];
if (this.isElement(element)) {
current_element = element;
while (this.isElement(current_element)) {
result.push(current_element);
current_element = current_element.parentNode;
}
}
return result;
};
CssSelectorGenerator.prototype.getTagSelector = function(element) {
return this.sanitizeItem(element.tagName.toLowerCase());
};
CssSelectorGenerator.prototype.sanitizeItem = function(item) {
var characters;
characters = (item.split('')).map(function(character) {
if (character === ':') {
return "\\" + (':'.charCodeAt(0).toString(16).toUpperCase()) + " ";
} else if (/[...