Whiteshadow
Whiteshadow

Reputation: 11

Selenium Java | Trouble finding/clicking button with xpath nested in class

Problem: I can't figure out how to click the specific button I need and how to make sure that button isn't highlighted.

1) On the main page, there is a button for each page. They all have their own close/report button.

2) I need to select ONLY non highlighted pages, and click THAT close button.

I can use this to click the button, but I don't know if it's highlighted or not.

By.xpath("//button[@type='button'])[8].click();

I tried doing something like this, but it didn't work:

By.xpath("//li[@class='media'] and //button[@type='button']").click();

Here is what each page looks like. Some are highlighted, some are in the class name.

<li class="media highlighted">
<div class="media-options">
  <button type="button" class="close" title="Close page">Delete this page</button>
  <button type="button" class="report" title="Report page">Report this page</button>
</div>

<li class="media">
<div class="media-options">
  <button type="button" class="close" title="Close page">Delete this page</button>
  <button type="button" class="report" title="Report page">Report this page</button>
</div>

Upvotes: 1

Views: 746

Answers (2)

parishodak
parishodak

Reputation: 4676

You can get to know whether an element is highlighted or not from its css class attributes.

String liClassAttribute = driver.findElements("//li[@class='media'][1]").getAttribute("class");

Here I have explained, how to get class attribute of first li item.

However as per your question, you need to click on non-highlighted items. So get a list of all list items, get class attribute for each item of li and if its not highlighted, you can act as per your requirement.

Pseudocode:

List<WebElement> liElementList = driver.findElement("//li[@class='media']);
for(WebElement elem : liElementList) {
    String liClassAttr = liElementList[0].getAttribute("class");
    if ( !liClass.contains("highlighted")){
         // you found the non-highlighted list item
         // act on it or ignore it based on your business logic.
    }
 }

Upvotes: 0

Shubham Jain
Shubham Jain

Reputation: 17593

For delete this button :-

driver.findElement(By.xpath("//li[@class='media highlighted']//button[@class='close']"));

For Report this button :-

driver.findElement(By.xpath("//li[@class='media highlighted']//button[@class='report']"));

Upvotes: 1

Related Questions