-
Notifications
You must be signed in to change notification settings - Fork 6
/
css-path.js
60 lines (45 loc) · 1.41 KB
/
css-path.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
54
55
56
57
58
59
60
var trim = require('trim')
, classSelector = function (className) {
var selectors = className.split(/\s/g)
, array = []
for (var i = 0; i < selectors.length; ++i) {
if (selectors[i].length > 0) {
array.push('.' + selectors[i])
}
}
return array.join('')
}
, nthChild = function (elm) {
var childNumber = 0
, childNodes = elm.parentNode.childNodes
, index = 0
for(; index < childNodes.length; ++index) {
if (childNodes[index].nodeType === 1)
++childNumber
if (childNodes[index] === elm)
return childNumber
}
}
, path = function (elm, rootNode, list) {
var tag = elm.tagName.toLowerCase()
, selector = [ tag ]
, className = elm.getAttribute('class')
, id = elm.getAttribute('id')
if (id) {
list.unshift(tag + '#' + trim(id))
return list
}
if (className)
selector.push( classSelector(className) )
if (tag !== 'html' && tag !== 'body' && elm.parentNode) {
selector.push(':nth-child(' + nthChild(elm) + ')')
}
list.unshift(selector.join(''))
if (elm.parentNode && elm.parentNode !== rootNode && elm.parentNode.tagName) {
path(elm.parentNode, rootNode, list)
}
return list
}
module.exports = function (elm, rootNode) {
return path(elm, rootNode, []).join(' > ')
}