1

This question is geared towards testing via Selenium / Web Driver, though applies to general web application/development.

XPath has a very nice feature of grouping a given XPath and combining with indexing to say "give me element N for all/multiple elements returned from given XPath, specified as "(//someXpath)[n]" w/o the quotes.

I was wondering if there is a translatable equivalent in CSS. If not via standard CSS, then how about Sizzle/jQuery? If none exist, would be nice if that kind of thing be added as a CSS standard in the future. Something like a "(someCssSelector):nth-of-type(n)"

Other than that, the alternative for XPath and CSS is to be more specific in describing the DOM tree, going up the tree to get uniqueness in identifying elements (as opposed to (someShorterSimplerXpath)[n]).

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
David
  • 3,223
  • 3
  • 29
  • 41
  • It is as yet unclear whether the [`:nth-match()`](http://www.w3.org/TR/selectors4/#nth-match) pseudo-class in CSS4 will allow a list of complex selectors or only a list of simple selectors (see [this section](http://www.w3.org/TR/selectors4/#structure) for terminology). If it will allow complex selectors, it may very well be the future standard that you're hankering after :) – BoltClock Feb 25 '12 at 00:53
  • As an example, the XPath expression `(//foo/bar[@name])[n]` could translate to the following CSS4 selector: `:nth-match(n of foo > bar[name])`, where `foo > bar[name]` is a complex selector (following the syntax shown in the 2011 WD). But if `:nth-match()` doesn't accept complex selectors, then you won't be able to do this with pure CSS for a long, long while. – BoltClock Feb 25 '12 at 05:08
  • Thanks, that's insightful info. Hope :nth-match() will support complex selectors. – David Feb 27 '12 at 19:59
  • Just noticed you can get css count via javascript in a post http://stackoverflow.com/questions/1573170/how-can-i-count-the-number-of-elements-that-match-my-css-selector. The nth-match feature could potentially be useful to iterate over matches same as Selenium's getXpathCount and the parenthetical indexing method for XPath. – David Feb 28 '12 at 01:27

1 Answers1

1

You can access jquery sets like arrays: $('selector')[n]

For the relative / xpath, you can use children(), so for an xpath like //selector/foo you'd do $('selector').children('foo'). For the relative // xpath, you can use find(): for //selector//foo use $('selector').find('foo'). For .. you can use parent(): for //selector/.. use $('selector').parent()

With CSS, while there are no parent selectors, there is an nth-of-type pseudo-class (specification here). So you can do selector:nth-of-type(n).

beerbajay
  • 19,652
  • 6
  • 58
  • 75