View Javadoc

1   package com.atlassian.webdriver.utils.by;
2   
3   import org.openqa.selenium.By;
4   import org.openqa.selenium.SearchContext;
5   import org.openqa.selenium.WebElement;
6   
7   import java.util.List;
8   
9   /**
10   * Extensions of {@link org.openqa.selenium.By} to locate elements by HTML5 data-* attribute.
11   *
12   * @since v2.1
13   */
14  public final class ByDataAttribute
15  {
16      private abstract static class ByData extends By
17      {
18          /** Override to avoid a stack overflow in {@link Object#toString} and {@link By#hashCode}. */
19          @Override
20          public String toString()
21          {
22              return "ByData";
23          }
24      }
25  
26      private ByDataAttribute()
27      {
28          throw new AssertionError("Don't instantiate me");
29      }
30  
31  
32      public static By byData(final String attributeName)
33      {
34          return new ByData()
35          {
36              @Override
37              public List<WebElement> findElements(SearchContext context)
38              {
39                  return context.findElements(By.cssSelector(String.format("*[data-%s]", attributeName)));
40              }
41          };
42      }
43  
44      public static By byData(final String attributeName, final String attributeValue)
45      {
46          return new ByData()
47          {
48              @Override
49              public List<WebElement> findElements(SearchContext context)
50              {
51                  return context.findElements(By.cssSelector(String.format("*[data-%s=\"%s\"]", attributeName, attributeValue)));
52              }
53          };
54      }
55  
56      public static By byTagAndData(final String tagName, final String dataAttributeName)
57      {
58          return new ByData()
59          {
60              @Override
61              public List<WebElement> findElements(SearchContext context)
62              {
63                  return context.findElements(By.cssSelector(String.format("%s[data-%s]", tagName, dataAttributeName)));
64              }
65          };
66      }
67  
68      public static By byTagAndData(final String tagName, final String dataAttributeName, final String dataAttributeValue)
69      {
70          return new ByData()
71          {
72              @Override
73              public List<WebElement> findElements(SearchContext context)
74              {
75                  return context.findElements(By.cssSelector(String.format("%s[data-%s=\"%s\"]", tagName,
76                          dataAttributeName, dataAttributeValue)));
77              }
78          };
79      }
80  }