12

If I have the following HTML:

<tbody id="items">
<tr><td>Item 1</td></tr>
<tr><td>Item 2</td></tr>
<tr><td>Item 3</td></tr>
<tr><td>Item 4</td></tr>
<tr><td>Item 5</td></tr>
<tr><td>Item 6</td></tr>
</tbody>

How would I use CSS selectors with Selenium to access Item 4(or really any item I wanted)?

5 Answers 5

22

You can use nth-child selector:

#items tr:nth-child(4) {color:#F00;}

Live example: https://jsfiddle.net/7ow15mv2/1/

But no idea if it works with Selenium.

But according to docs it should.

Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after).

Sign up to request clarification or add additional context in comments.

3 Comments

I haven't explored this, but in CSS isn't the :nth-child() selector zero-based? (My understanding is that the fourth row would be :nth:child(3), though I could very definitely be completely wrong.)
w3.org/TR/css3-selectors/#nth-child-pseudo "The index of the first child of an element is 1".
For the 4th column in the 5th row: document.querySelector("tr:nth-child(5) td:nth-child(4)")
2

you can try this for searching by any inner text

css=td:contains('Item 4')

found this helpful: http://saucelabs.com/blog/index.php/2010/01/selenium-totw-css-selectors-in-selenium-demystified/

1 Comment

where did you find ':contains' documented? it's not on the link you provided, nor does it work when I try it in the browser console, says it's not a valid selector. Is this something that was around for a bit and then removed from CSS later?
0

Do you want to select by content ("Item 4")? By Position (the 4st row)? Or is <tr id="foo"> and selecting tr#foo>td an option?

1 Comment

position only without adding any extra HTML
0

You could use xpath to find it in a number of different ways but the easiest is:

//td[text()='Item 4']

Comments

0
selenium.getText("css=table>tbody[id=items]>tr:nth-child(3)>td(3)");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.