Garrarufa Garrarufa - 1 year ago 70
CSS Question

How to select the nth html element in a table that has special class?

I am using Nightwatch.js to test a website. On this website there is a table which looks like this:

<td class="sorting_1">...</td>
<td class="sorting_2">...</td>
<td class="sorting_3">...</td>
<td class="sorting_3">...</td>

Now I want to check if this table contains the correct words. I found out that it is possible to select an element this way:


I can get the text with this command:

.getText('td[class="sorting_2"]', function(result){
this.assert.equal(result.value, 'Testbenutzer');

But what do I have to do if I want to select one of two equally defined elements like in the list above. The last two elements both have the class
. How can I get the nth element of the table with a special class.
I already tried this:


Nothing of this worked. How can I do it?

Answer Source

The only way I can think of accessing multiple .sorting_3 elements, without knowledge of how Nightwatch.js actually works, is to pass it siblings ~ combinator selector.

i.e.: when you want to select the first element out of .sorting_3 elements, you would do this:

.getText('td[class="sorting_3"]', function(result){
    this.assert.equal(result.value, 'Testbenutzer');

And for second element:

.getText('td[class="sorting_3"] ~ td[class="sorting_3"]', function(result){
    this.assert.equal(result.value, 'Testbenutzer');

And so on ...

Problem is, this approach is not scalable. You will need to know ahead of time how many elements are you expecting in the .sorting_3 selector.

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download