How to check if element contains specific class attribute

前端 未结 7 1743
生来不讨喜
生来不讨喜 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:14

      The answer provided by @drkthng works but you might have a case where the class name is a subset of another class name. For example:

    • text
    • If you wanted to find the class "item" then the provided answer would give a false positive. You might want to try something like this:

      public boolean hasClass(WebElement element, String htmlClass) {
          String classes = element.getAttribute("class").split("\\s+");
          if (classes != null) {
              for (String classAttr: classes) {
                  if (classAttr.equals(htmlClass)) {
                      return true;
                  }
              }
          }
          return false;
      }
      

    提交回复
    热议问题