How to check if element contains specific class attribute

前端 未结 7 1740
生来不讨喜
生来不讨喜 2021-02-05 02:09

How can I check if a selenium web element contains a specific css class.

I have this html li element

  • 7条回答
    •  死守一世寂寞
      2021-02-05 02:17

      Given you already found your element AND you want to check for a certain class inside the class-attribute:

      public boolean hasClass(WebElement element) {
          String classes = element.getAttribute("class");
          for (String c : classes.split(" ")) {
              if (c.equals(theClassYouAreSearching)) {
                  return true;
              }
          }
          
          return false;
      }
      

      #EDIT As @aurelius rightly pointed out, there is an even simpler way (that doesn't work very well):

      public boolean elementHasClass(WebElement element, String active) {
          return element.getAttribute("class").contains(active);
      }
      

      This approach looks simpler but has one big caveat:

      As pointed out by @JuanMendes you will run into problems if the class-name you're searching for is a substring of other class-names:

      for example class="test-a test-b", searching for class.contains("test") will return true but it should be false

      #EDIT 2 Try combining the two code snippets:

      public boolean elementHasClass(WebElement element, String active) {
          return Arrays.asList(element.getAttribute("class").split(" ")).contains(active);
      }
      

      That should fix your caveat.

    提交回复
    热议问题