How to select span elements of specific container (<div> defined by CSS class) using Xpath?

Viewed 56

i have the following HTML stucture :

  <div class="divone"><span class="my_sapn">Sports</span></div>
  <div class="divtwo"><span class="my_sapn">Arts</span></div>
  <div class="divtwo"><span class="my_sapn">Computer</span></div>
  <div class="divone"><span class="my_sapn">Fashion</span></div>
  <div class="divtwo"><span class="my_sapn">Familly</span></div>

What i want to achive is get all elements that have the class my_span inside the divs that have the class divone only.
my code get all span with the class my_span, output : Sports, Arts , Computer , Fashion , Familly
the desired output : Sports , Fashion
Mycode :

List<WebElement> MainCategory = driver.findElements(By.xpath("//span[@class=\"my_span\"]"));

PS : i must use By.xpath not By.classame

1 Answers

One way to achieve this result is using the following XPath-1.0 expression:

List<WebElement> MainCategory = driver.findElements(By.xpath("//div[@class='divone' and span/@class='my_span']/span"));

Another way to achieve the same output is

List<WebElement> MainCategory = driver.findElements(By.xpath("//span[../@class='divone' and @class='my_span']"));

The output in both cases is the same:

Sports
Fashion

Related