Forum Discussion

sergi's avatar
sergi
Contributor
8 years ago

How can I find a web element using class name

I need to find a web element that I know it has a specific class (but it's not the only class it has).

I can't find any suitable implementation of ISearchPattern that does that.

Am I missing something? It seems like a must have feature to find web elements.

 

FYI, with selenium it was something like.. 

By.className("className")

4 Replies

  • Hi,

     

    You can add custom properties to the web element search pattern using the Add method as described in the "Understanding Object Identification" article. Here is a quick and simple example:

     

                IControl panel = driver.Find<IWebBrowser>(new WebBrowserPattern()
                {
                    ObjectIdentifier = "chrome"
                }).Find<IWebPage>(new WebPagePattern()
                {
                    URL = "https://smartbear.com/"
                }).Find<IControl>(new WebElementPattern()
                {
                    ObjectType = "Form",
                    idStr = "form"
                }).Find<IControl>(new WebElementPattern()
                {
                    ObjectType = "Panel",
                }.Add("className", "nav-addition*"), 6);

     

    Hope this helps!

    • sergi's avatar
      sergi
      Contributor

      Thanks for the reply.

      I am aware of the Add method. My question was more focused on the fact of having multiple classes applied to an element.

       

      Is the "*" (in "nav-addition*") doing the trick?

  • Hi,

    You wont be able to use a search pattern in this case as className  property does not exist in any of the search patterns. The work around for this is as below

     

    IEnumerable<IWebElement> panelObjects = page.FindAll<IWebElement>(new WebCellElementPattern
                    {
                        objectType = "Panel"                    
                    }, 1000,3000)
    IWebObject myPanelObject = panelObjects.Where(l => l.GetProperty<string>("className").Contains("yourclassname"))

    You can filter the object with class name you want using LINQ on the collection

    panelObjects 

    .

    • sergi's avatar
      sergi
      Contributor

      Thanks for the suggestion.

      I was looking for something more straightforward and less like a workaround, but I've already had to do this in other use cases.