0

I've got a table and need to find a specific row number. In this case, I'm interested in the 2nd row (2nd tr).

Here's the HTML:

<table>
  <thead>
    <tbody>
      <tr class="classes mico_models_classes_7 listRowWhite">
      <tr class="classes mico_models_classes_8 listRowDark">
         <td style="width:130px;">9:00am - 10:30am</td>
         <td class="noprint enrolledFull" style="width:70px;height:40px;text-align:center;">   </td>
         <td style="width:200px;">
         <a class="eventName" data-eventdescription="Very long spin class" data-eventname="Spinning 90 min" href="javascript://">Spinning 90 min</a>
        <br>
       with
       <a class="classesEmployeeName" title="John Doe" href="javascript://" data-employeeid="5117">John Doe</a>
      </td>
    <td style="text-align:right;width:72px;">0 of 20</td>
   <td>Spin Class</td>
  </tr>
  <tr class="classes mico_models_classes_9 listRowWhite">
  <tr class="classes mico_models_classes_10 listRowDark">
 </tbody>
</table>

Unfortunately, the following returns null for dataRowIndex:

String classTittle = "Spinning 90 min";
String dataRowIndex = driver.findElement(By.cssSelector("[data-eventname='" + classTitle + "']")).getAttribute("rowIndex");

1 Answer 1

1

You can solve this by iterating the tr HTML-elements while counting them. You can also access them while iterating.

List<WebElement> element = driver.findElements(By.cssSelector("tr"));

        int row = 0;

        for( WebElement w : element){

            String elemText = w.getText();

            System.out.println(elemText);

            String clickText = "Spinning 90 min";

            if(elemText.contains(clickText)){

                w.click(); //do something with the element

                System.out.println("Text in row " + row + " is " + clickText + " so i clicked it!");
            }

            System.out.println("this was row " + row + "\n");

            row++;
        }

Will yield:

this was row 0

9:00am - 10:30am Spinning 90 min
with John Doe 0 of 20 Spin Class
Text in row 1 is Spinning 90 min so i clicked it!
this was row 1


this was row 2


this was row 3

You might want to encapsulate your specific logic in a method later on. Hope this helps ^^-d

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

1 Comment

I was assuming that the findelement would work and could avoid the iteration, but I couldn't get it to work.Your iteration worked perfectly, thanks for that!

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.