1

I have a list of elements which I have to scan using the iterator, and click on the desired element.

List <WebElement> lt = driver.findElements(By.tagName("strong"));
  Iterator <WebElement> it= lt.iterator();
  while(it.hasNext())
  {
   if(it.next().getText().equals(cat))
   {
    it.next().click();
    break;
   }
  }

In my code, when the iterator finds the element, the execution goes inside the if loop, but selects the next element, when it encounters it.next().click(); how do I click on the current element that has been pointed by the if loop?

Gaurav Thantry
  • 753
  • 13
  • 30

2 Answers2

2

Each time you call it.next(), you get the next element AND move the cursor ahead.

Instead, store the instance, do the check and execute the click on it like:

WebElement e;
while(it.hasNext())
    e = it.next();
    if(e.getText().equals(cat)) {
        e.click();
    }
}
AxelH
  • 14,325
  • 2
  • 25
  • 55
2

Using a for() loop may cater to our needs in a easier way as follows:

    List <WebElement> lt = driver.findElements(By.tagName("strong"));
    for(WebElement it:lt)
    {
        String my_text = it.getText();
        if(my_text.contentEquals("cat"))
        {
            it.click();
            break;
        }
    }
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • That's an alternative, but doesn't really answer the question "_How do you click on the current element using iterator_" – AxelH Sep 07 '17 at 09:09
  • @AxelH IMO, `iterator` best fits into usecases where we need to iterate to the next items/nodes. Here OP's requirement is to validate a property in the current/present item/node. Hence `for()` seems to be the best fit. Yes, it can also be achieved through `iterator` as well. – undetected Selenium Sep 07 '17 at 09:23
  • 1
    That was not my point ;) the question is about `Iterator`, FYI : **1)** the `for` loop will create the iterator for you, so it is doing the same thing, see [this thread](https://stackoverflow.com/a/18410489/4391450). **2)** `Iterator` is good to "iterate" a `Collection` and be able to update it (you can't remove an item on your loop, `ConcurrentModificationException` occurs). But also give you a simple solution to read a collection without managing the length (same as yours but with a concurrent access since you don't have the iterator if needed) – AxelH Sep 07 '17 at 09:46