css-path
css-path copied to clipboard
gets the wrong selector when :nth-child is needed higher in the tree
how to reproduce:
go to http://www.amazon.de/dp/B00KX14CY6?psc=1
insert css-path
sourcecode
write in the console
el = document.querySelector("li:nth-child(3) #a-autoid-2 > span.a-button-inner > input.a-button-input") //second image
el2 = document.querySelector(cssPath(el, document))
el === el2 // false
Hey @dbuezas
Thanks for the reporting the issue.
css-path assumes that ids are unique on a page - but on the amazon-page that you linked to there are, in fact, 3 elements with the id #a-autoid-2
so then it doesn't work as expected.
Since id's are supposed to be unique to a page I don't really know what to do in this case TBH. Do you have a suggestion?
Hey @kesla thanks for the feedback. I see the problem now, it was not what I thought (I tried many libraries and all of them have the same problem, I assumed the reason was also the same)
you're right, they're supposed to be unique, but as browsers tolerate that it would be nice to support this.
maybe something like this?
// line 37
if (id) {
list.unshift( tag + '#' + trim(id) )
if (rootNode.querySelectorAll(list.join('>')).length > 1){
selector.push( list.shift() )
} else {
return list
}
}
Haven't tested it yet but I think it makes sense. It would be slower but uniqueness should also be guaranteed in that case.
What do you think?
this works:
if (id) {
list.unshift( tag + '#' + trim(id) )
var isUnique = rootNode.querySelectorAll(list.join('>')).length === 1
if (isUnique){
return list
} else {
list.shift()
selector.push('#' + trim(id))
}
}
Looks great! I'd gladly accept a PR for that :)