views:

658

answers:

2

Even though I am going to use this CSS selector in Selenium, this should be generic enough.

I have a page with table of class "list" & it can occur multiple times. I want to find out each occurrence & how many rows each table has. So for this I could use table[class='list'] & will give me all the tables of that class in the page. In this example lets us say it is 3. Now I want to iterate through each of those table, so I tried table[class='list']:nth-child(1) for the first occurrence & table[class='list']:nth-child(2) for second occurrence & so on. I thought that table[class='list']:nth-child(1) would give me the first occurrence but I cannot use the nth-child(n) notation.

If I use table[class='list']:nth-child(odd), I do get all the odd numbered table, but I cannot specifically target a specific table by saying table[class='list']:nth-child(3). It gives me no result back. What am I doing wrong?

BTW, I am using "FireFinder" addon for Firebug to evaluate my CSS selectors on the test page.

+1  A: 

table[class='list']:nth-child(1) will match all table elements with a class of list that are the first child of their parent. It has nothing to do with how many elements are matched or what the order of that set is, though if all the tables had the same parent (and that parent had no other children) then your method would work.

You may be able to iterate through the elements returned by table.list some other way, or somehow change your selector the exact details of which would depend on the actual structure of your page.

CurtainDog
That actually clears up some confusion I had, but in this case, luckily, they all have the same parent. That is all these tables are within another table cell. That is the HTML would losely look like:<code>...<td> <table class="list"... <table class="list"...</td>...</code>
John
An addendum to that - if I use table[class='list']:nth-child(1) does that mean it has to be the first child or the first "matched" child since I am trying to match the first table of the type list.
John
As I understand it, it's the nth-child irrespective of [class='list'].
nullptr
John
You can use `nth-of-type` to eliminate the `<br/>`, but that still won't take into account your class filter. I don't think CSS has the power you need here on its own. I would suggest using XPath or scripting it.
nullptr
A: 

Perhaps XPath would suit you better?

//table[@class='list' and position()=1]
//table[@class='list' and position()=2]
...
nullptr
Actually we had all our selectors in XPath initially, but since it was slower in IE we're converting our selectors to CSS which is much faster
John
Good to know. I generally use CSS when it's more compact, and XPath when it is more reliable. It's quite nice to be able to mix and match regardless of performance.
nullptr