</>

Technology

Selenium

Difficulty

Beginner

Interview Question

What is the syntax of finding elements by class using CSS Selector?

Use dot notation (.className) in CSS Selector to find elements by their class attribute.

Answer

In CSS Selector, the dot (.) notation selects elements by class name.

Syntax:

CSS
.className
tagName.className

Java examples:

Java
driver.findElement(By.cssSelector(".btn-primary"));
driver.findElement(By.cssSelector("button.btn-primary"));
driver.findElement(By.cssSelector(".btn.btn-large"));
driver.findElement(By.cssSelector("form .input-field"));
driver.findElement(By.cssSelector("div > .submit-btn"));

By.className() vs By.cssSelector():

MethodExampleNotes
By.className()By.className("btn")Single class only
By.cssSelector()By.cssSelector(".btn.active")Supports multiple classes

Important: By.className() does NOT support multiple classes — use CSS Selector for that: By.cssSelector(".btn.active")

Follow AutomateQA

Related Topics