I am building a selenium-based test application uses CSS Selectors or XPath strings, and am attempting to test menu items that appear on hover. Using "Inspect Element" in Chrome and in FireFox by right clicking, can verify that the right html is being highlighted, but when I copy the CSS Selector or the XPath, it sometimes selects multiple elements. For instance:
"#myId > li:nth-child(2) > a"
was what Chrome gave me, but it represents 13 elements in the DOM (each in a different sub-menu). The selector I need is the ninth element of the selector's result:
$("#myId > li:nth-child(2) > a")[9]
My main question is whether this can be represented as a CSS selector? I searched for an example but didn't find this particular problem.
$("#myId > li:nth-child(2) > a(9)")
Does not work - returns empty array.
CSS does not provide a selector for the nth element matching some complex selector. jQuery makes up for this with the :eq() selector:
$("#myId > li:nth-child(2) > a:eq(8)")
Note that :eq() is 0-indexed, unlike :nth-child() which is 1-indexed, so this will return the ninth element that matches the selector #myId > li:nth-child(2) > a.
The equivalent XPath, should you choose to use that instead, is:
(id('myId')/li[2]/a)[9]
Your situation is unique, however, because if we assume that #myId is unique, as it should be, then you can use the CSS pseudo-class :nth-of-type() to find the ninth a child of the second li child of the element #myId:
$("#myId > li:nth-child(2) > a:nth-of-type(9)")
Note that :nth-of-type() and :eq() are not the same. :nth-of-type() behaves much like :nth-child() in that it considers children of the same parent, except that it looks at the element type, or the tag name. In this case, the element type we're concerned with is a.
The use of > combinators in your existing selector implies a parent-child relationship between your li and a elements, which is compatible with the :nth-of-type() selector. This is why I believe it can be used in your specific situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With