About this lesson
By.className in Selenium Java: find an element by one CSS class
Selenium Java AssignmentsBeginnerLocators
How it works
By.className("value") finds elements that have that class among the space-separated names in their class attribute. A field with the classes pt-1 pb-1 pr-2 pl-2 matches By.className("pb-1"), because only one name in the list has to match.
It takes exactly one class name. Passing two, such as By.className("pt-1 pb-1"), throws InvalidSelectorException with the message that compound class names are not permitted. To require several classes at once, use a CSS selector like .pt-1.pb-1, which lesson 11 introduces.
Classes usually describe how something looks, so many elements share them. On Text Fields, seven fields carry the padding class pt-1, but only the last-name box has last-name-input, a class that names its purpose.
About the assignment
The last-name box on Text Fields carries the class last-name-input. You will locate it by that class alone and confirm you got the right element by reading its id.
What you will do
- Find the element with
driver.findElement()andBy.className(), passing the single class name. - Read the
idattribute of the element that comes back. - Print it after the label
Element ID:.
Common mistakes
Including the dot
By.className()wants the bare name. A leading dot is CSS syntax;By.className(".last-name-input")looks for a class literally called.last-name-inputand throwsNoSuchElementException.Picking a layout class
Classes such as
pt-1orcol-6appear on many elements and change whenever a designer adjusts spacing.findElement()returns the first of them, which is rarely the one you wanted.Passing the whole class attribute
Copying every class from DevTools into
By.className()triggers the compound class error described above.
In a real test suite
Class locators work well when the front end adds purpose-named classes such as error-message or cart-total. Many teams go one step further and add data-testid attributes that exist only for tests.
Lesson 7 goes broader still and selects elements purely by their tag name.
Related lessons
- CSS Selectors - BasicsCSS
.classandtag.classselectors, including several classes at once. - Find Element by Tag NameLocate by tag name when an element has no distinctive class at all.
- Get CSS Value with getCssValue()Read the CSS a class applies with
getCssValue().
To try one of these calls on any page without a task, open the online Selenium compiler for Java.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://testkru.com/Elements/TextFields");
// TODO: Find element by className "last-name-input"
// TODO: Print its ID attribute
driver.quit();
}
}