I got this function to get a cssPath :
JavaScript
x
14
14
1
var cssPath = function (el) {
2
var path = [];
3
4
while (
5
(el.nodeName.toLowerCase() != 'html') &&
6
(el = el.parentNode) &&
7
path.unshift(el.nodeName.toLowerCase() +
8
(el.id ? '#' + el.id : '') +
9
(el.className ? '.' + el.className.replace(/s+/g, ".") : ''))
10
);
11
return path.join(" > ");
12
}
13
console.log(cssPath(document.getElementsByTagName('a')[123]));
14
But i got something like this :
html > body > div#div-id > div.site > div.clearfix > ul.choices > li
But to be totally right, it should look like this :
html > body > div#div-id > div.site:nth-child(1) > div.clearfix > ul.choices > li:nth-child(5)
Did someone have any idea to implement it simply in javascript ?
Advertisement
Answer
To always get the right element, you will need to use :nth-child()
or :nth-of-type()
for selectors that do not uniquely identify an element. So try this:
JavaScript
1
18
18
1
var cssPath = function(el) {
2
if (!(el instanceof Element)) return;
3
var path = [];
4
while (el.nodeType === Node.ELEMENT_NODE) {
5
var selector = el.nodeName.toLowerCase();
6
if (el.id) {
7
selector += '#' + el.id;
8
} else {
9
var sib = el, nth = 1;
10
while (sib.nodeType === Node.ELEMENT_NODE && (sib = sib.previousSibling) && nth++);
11
selector += ":nth-child("+nth+")";
12
}
13
path.unshift(selector);
14
el = el.parentNode;
15
}
16
return path.join(" > ");
17
}
18
You could add a routine to check for unique elements in their corresponding context (like TITLE
, BASE
, CAPTION
, etc.).