Daredevi1
Daredevi1

Reputation: 103

Click on particular instance for a button using CSS selector

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>

Upvotes: 1

Views: 646

Answers (1)

Norayr Sargsyan
Norayr Sargsyan

Reputation: 1868

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();
    });

Upvotes: 1

Related Questions