css-path icon indicating copy to clipboard operation
css-path copied to clipboard

gets the wrong selector when :nth-child is needed higher in the tree

Open dbuezas opened this issue 9 years ago • 4 comments

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

dbuezas avatar Oct 07 '15 17:10 dbuezas

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?

kesla avatar Oct 08 '15 07:10 kesla

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?

dbuezas avatar Oct 08 '15 13:10 dbuezas

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))
          }
        }

dbuezas avatar Oct 08 '15 17:10 dbuezas

Looks great! I'd gladly accept a PR for that :)

kesla avatar Oct 08 '15 18:10 kesla