1

I have a webpage which has multiple submit buttons. I want to loop through them and click on each of them one by one.

I know I can do it via xpath like this (//button[@class='submit'])[i] (where i = loop number).

But I wanted to know if it's possible to do via CSS selector?

I've tried button.submit but it will always click on the first button and I want to be able to loop through. I've also tried button.submit:first-child but it seems to do the same thing.

The following is similar to what the HTML is like.

<div>
    <button class="submit" type="button"></button>
</div>
<div>
    <button class="submit" type="button"></button>
</div>
<div>
    <button class="submit" type="button"></button>
</div>
2
  • Did you try to loop() to be able to loop? Commented Jul 23, 2020 at 19:32
  • The loop isnt the issue. I need the css selector for my element. Commented Jul 23, 2020 at 20:19

1 Answer 1

1

Yes, you can do this such way:

If you are using Java version less than 8 do this way:

List<WebElement> elements = driver.findElements(By.cssSelector("button.submit"));

WebElement confirm = driver.findElement(By.cssSelector("selector_for_confirm"));

for(WebElement element: elements){
     element.click();
     confirm.click();
}

If you are using Java 8 or above, you can try this way:

List<WebElement> elements = driver.findElements(By.cssSelector("button.submit"));

WebElement confirm = driver.findElement(By.cssSelector("selector_for_confirm"));

  elements.forEach(e->{
        e.click();
        confirm.click();
    });
Sign up to request clarification or add additional context in comments.

1 Comment

If I understand correctly this will click on each element one after the other. But what if after clicking each button there is a confirmation modal where you have to click confirm? For example you first click Submit, then you click confirm for each one.

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.