Skip to content

Instantly share code, notes, and snippets.

@joewright
Last active February 20, 2018 15:23
Show Gist options
  • Save joewright/8fc0a3acd21ae6fa04208e91a1f5f516 to your computer and use it in GitHub Desktop.
Save joewright/8fc0a3acd21ae6fa04208e91a1f5f516 to your computer and use it in GitHub Desktop.
log a unique jQuery selector for every element clicked on a page
// requires jQuery https://code.jquery.com/jquery-1.11.3.js
window.events = [];
$('body').click(function(event) {
//use event.target with firefox
var selector = fromHTMLElement(event.toElement || event.target);
window.events.push(selector);
console.log(selector, $(selector));
});
function fromHTMLElement(srcElement) {
var ngRegex = /ng-/ig;
var attributeIgnoreRegex = /ng-model-options|style/ig;
var querySelector = srcElement.tagName;
var attrs = srcElement.attributes;
if (attrs.length !== 0) {
for (var ix = 0; ix < attrs.length; ix++) {
var attribute = attrs[ix];
if (attribute.name === 'class') {
// clear angular classes
var classVal = attribute.value
.split(' ')
.filter(function(str) {
return !str.match(ngRegex);
})
.join('.');
if (classVal) {
querySelector += '.' + classVal;
}
} else if (attribute.name === 'id') {
querySelector += '#' + attribute.value;
} else if (!attributeIgnoreRegex.test(attribute.name)) {
querySelector += ('[' + attribute.name + '="' + attribute.value + '"]');
}
}
}
return uniqueSelector(querySelector, srcElement);
}
function uniqueSelector(querySelector, srcElement) {
var clickedElementIndex = -1;
var total = 0;
$.each($(querySelector), function(index) {
if (this === srcElement) {
clickedElementIndex = index;
}
total++;
});
if (clickedElementIndex !== -1 && total > 1) {
querySelector += ':eq(' + clickedElementIndex + ')';
}
return querySelector;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment