-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselector-generator.js
53 lines (45 loc) · 1.44 KB
/
selector-generator.js
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
var SPECIFIERS = [
// Tag Name
function(el, selector) {
return el.tagName.toLowerCase();
},
// Classes
function(el, selector) {
var classes = el.className.trim().replace(/\s+/g, '.');
return selector + (classes.length ? '.' + classes : '');
},
// Nth-Child
function(el, selector) {
var index = Array.prototype.slice.call(el.parentNode.children).indexOf(el) + 1;
return selector + ':nth-child(' + index + ')';
}
];
/**
* Generates increasingly specific CSS selectors for a given element
*
* @class SelectorGenerator
* @param {HTMLElement} element
* @param {HTMLElement} context
* @constructor
*/
module.exports = function* SelectorGenerator(element, context) {
var specificity = 0,
selector = '';
context = context || document;
while(element.parentElement && (element !== context)) {
// Build the top-level selector for this depth and specificity
var item = SPECIFIERS.slice(0, specificity + 1).reduce(function(memo, fn) {
return fn(element, memo);
}, ''),
tail = selector.length ? ' > ' + selector : '';
// Increment specificity
specificity = (++specificity % SPECIFIERS.length);
// Ascend the DOM
if(specificity === 0) {
element = element.parentElement;
selector = item + tail;
}
// Yield
yield item + tail;
}
}