We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Use By.cssSelector with id, attributes, and substring patterns.
CSS selectors are a powerful and flexible way to locate elements in Selenium. They are often simpler and more readable than complex XPath and are supported by all modern browsers.
In Selenium, we use them through: By.cssSelector("...")
What it does
Uses the # symbol followed by the element’s id.
Example: #fname → element with id="fname".
id and want to stay in CSS world.What it does
Targets any attribute, not only id or name.
Example: input[name='lname']
id or you want to be explicit about the element type.^= – starts with$= – ends with*= – containsExample: input[placeholder^='Enter your']
Practice targeting these elements using CSS selectors!
123456789101112131415WebElement firstNameInput = driver.findElement(By.cssSelector("#fname"));
firstNameInput.clear();
firstNameInput.sendKeys("Jane");
WebElement lastNameInput = driver.findElement(By.cssSelector("input[name='lname']"));
lastNameInput.clear();
lastNameInput.sendKeys("Doe");
WebElement emailInput = driver.findElement(By.cssSelector("input[placeholder^='Enter your']"));
emailInput.sendKeys("student@example.com");
WebElement newsletterCheckbox = driver.findElement(By.cssSelector("input[value*='newsletter']"));
newsletterCheckbox.click();
driver.quit();#fname to locate the first name input (id="fname").<input> with name="lname" (the last name field).^=) on the placeholder attribute. This matches the email field with placeholder starting "Enter your...".*=) on the value attribute. It finds the checkbox whose value contains "newsletter".If you already use CSS in your project, By.cssSelector keeps everything consistent and is usually more concise than XPath.
You can mix IDs, classes, and attributes in one selector (e.g. input#fname.required) for precise targeting.
Substring selectors (^=, $=, *=) are powerful, but make sure the piece you match is unique enough.