Search code examples
javascriptseleniumselenium-webdriverintern

How do I break a loop of elements in intern


Let's say I have the following DOM structure

<table id="campaigns">
   <tr>
      <th>Name</th>
      <th>Status</th>
   </tr>
   <tr>
      <td>first data</td>
   </tr>
   <tr data-id="1">
      <td>intern test at Fri, 09 Dec 2016 03:12:26 GMT</td>
   </tr>
   <tr data-id="2">
      <td>intern test at Fri, 09 Dec 2016 03:12:26 GMT</td>
   </tr>
   <tr data-id="3">
      <td>intern test at Fri, 09 Dec 2016 03:12:26 GMT edit</td>
   </tr>
   <tr data-id="4">
      <td>another data</td>
   </tr>
   <tr data-id="5">
      <td>next data</td>
   </tr>
</table>

and this is how i do it in intern

this.remote
     .findAllByXpath("//*[@id='campaigns']/tr"") //  get allitem from list
        .then(function (options) {
            return Promise.all(options.map(function (option) {
                return option.getVisibleText()
                    .then(function (text) {
                        if (text.includes("intern test")) {  //   checked whether the value is exist
                             option.click(); // click the value
                        }
                         return text;
                    })
            }))
         })

my requirement is only to click one the text that contain "intern test". This code seems fine but what happens is that when intern already clicking the first element in the if statement, the next element seems will also perform the click and stale the element. How do I stop this loop and proceed when it found the 1st element?

Thanks for any help provide


Solution

  • There is no need to go through all the elements to find the first element containing text "intern test"

    Try the following XPath using findAllByXpath (I am not aware of Javascript - selenium, so, please correct the syntax if required):

    //table[@id='campaigns']/tbody/tr/td[contains(text(),'intern test')]/..
    

    returns all the tr elements with text containing intern test inside the table with id campaigns.

    Use indexing, like 0, 1, 2 to match first, second and third elements containing intern test