In CSS Selector, the hash (#) notation selects elements by their id attribute.
Syntax:
CSS
#idValue
tagName#idValue
Java examples:
Java
driver.findElement(By.cssSelector("#username"));
driver.findElement(By.cssSelector("input#username"));
driver.findElement(By.cssSelector("#loginForm .submit-btn"));
driver.findElement(By.cssSelector("#container input[type=''text'']"));
Comparison:
| Locator | Syntax | Notes |
|---|---|---|
By.id() | By.id("username") | Simplest, fastest |
CSS #id | By.cssSelector("#username") | More flexible, can chain |
XPath @id | By.xpath("//input[@id=''username'']") | Verbose |
Best Practice: For elements with unique IDs,
By.id()is fastest. Use CSS#idwhen you need to combine with other selectors like#form input[type=''text''].
