How To Locate Web Element Which Has Multiple Class Names

A web element of a web page may belong to multiple classes. These classes may represent a class in style sheet or can be used for DOM manipulation. All belonging class names of a web element are mentioned under “class” attribute separated by a space. For example :-

We will see how can we locate these type of elements in Selenium WebDriver.

If you inspect “From” text box at Yatra then you will find it has multiple classes which is also called compound class names.

Let’s use className locator and see what happens.

Selenium WebDriver Java Code


When we pass all class names in className attribute it has thrown above exception because class attribute has compound class names i.e. required_field, cityPadRight, ac_input and origin_ac. This is not permitted by classname locator in Selenium WebDriver.

You can use classname locator with individual class names as below:

You can use findElements() with index or Xpath with index to get exact web element. Using index makes locator flaky as it may change based on addition or remove or modification of elements in DOM.

We can use xpath and cssSelector to locate web elements with multiple or compound class names. Use “class” as attribute and its complete value as it is in quotations for XPath and CSS Selector. Example is shown as below :-

But cssselector has multiple ways to locate web element with compound class names.

You can combine all class names with dot (.) and prefix by node i.e. tagName.classname1.classname2.classname3. For example Above node is “input” so another css selector can be written as :-


If you do not want to specify node name or want it to be any tag name then combine all class names with dot (.) and append a dot (.) in beginning which generally represents a class value in cssSelector i.e. .classname1.classname2.classname3


Selenium WebDriver Java code with all solutions

You can download/clone above sample project from here.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.

Find all Selenium related post here, all API manual and automation related posts here and find frequently asked Java Programs here.

Many other topics you can navigate through menu.

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Writing technical posts and creating YouTube videos are my hobbies.

7 thoughts on “How To Locate Web Element Which Has Multiple Class Names

  1. Hi, Amod!
    Thanks for sharing this!
    I’ve found out that it works also by enclosing the multiple classes’ names in single quotes, i.e.:
    driver.findElement(By.cssSelector(“input[class = ”
    + “‘”
    + “required_field cityPadRight ac_input”
    + “‘”
    + “]”));

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.