</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

How can we select elements by their attribute value using CSS Selector?

Use [attribute=value] bracket notation in CSS Selector to select elements by any attribute and value.

Answer

Use square bracket [attribute=value] notation in CSS Selector to select elements by any attribute.

Basic examples:

Java
driver.findElement(By.cssSelector("[type=''submit'']"));
driver.findElement(By.cssSelector("input[type=''text'']"));
driver.findElement(By.cssSelector("[placeholder=''Enter email'']"));
driver.findElement(By.cssSelector("[name=''username'']"));
driver.findElement(By.cssSelector("input[type=''password''][name=''pwd'']"));

Partial Attribute Matching:

OperatorMeaningExample
[attr=''val'']Exact match[type=''text'']
[attr^=''val'']Starts with[id^=''user'']
[attr$=''val'']Ends with[id$=''name'']
[attr*=''val'']Contains[id*=''user'']
Java
driver.findElement(By.cssSelector("input[id^=''user'']"));
driver.findElement(By.cssSelector("button[class*=''btn'']"));

Follow AutomateQA

Related Topics