'CSS selectors How to get the index of a particular element

I am trying to use a css selector to select and item but only work for xpath. What would be the equivalent of this xpath to css.

driver.findElement(By.xpath("(//img[@alt='Authorise this row'])[2].click();

If I use the css img[alt='Authorise this row'] I get a lot of results through say firefinder. Is there a way like xpath where you can get a particular index of the result



Solution 1:[1]

CSS3 supports the :nth-child selector. For example, the following CSS targets only the second image:

img:nth-child(2) {...}

The argument to :nth-child can be either an index, keyword(e.g. odd, even), or a formula. The selector above selects all second image children of their parents. You could target it a bit more with something like:

#container img:nth-child(2)

Reference: :nth-child

Alternately, you could use jQuery to select a set of elements, and then reference one of them by index. Like so:

var secondImage = $('img')[2];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1