function checkSelector selector return document querySelectorAll selec

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function checkSelector(selector) {
return document.querySelectorAll(selector).length == 1;
}
function generateSelector(target, i) {
i = i || 0;
var baseSelector = target.tagName.toLowerCase();
if(target.hasAttribute('id')) {
baseSelector += '#' + target.getAttribute('id').trim();
if(checkSelector(baseSelector)) return baseSelector;
}
if(target.hasAttribute('class')) {
baseSelector += '.' + target.classList.toString().trim().split(' ').join('.');
if(checkSelector(baseSelector)) return baseSelector;
}
if(i > 2) {
return false;
}
var parentSelector;
if(!(parentSelector = generateSelector(target.parentNode, ++i))) {
return false;
} else {
return parentSelector + ' > ' + baseSelector;
}
}