Selenium WebDriver Locators & Element Identification 2 — Questions and Answers
Question 1: In CSS selector syntax used with Selenium, which symbol is used to target an element by its ID attribute?
- .
- # (Correct answer)
- @
- *
Correct answer: #
The `#` symbol is the CSS ID selector, so `#loginBtn` targets the element with `id="loginBtn"`.
Question 2: What does the XPath expression `//div[@class='menu']//a` select?
- All `a` elements that are direct children of div elements with class 'menu'
- All `a` elements anywhere inside div elements with class 'menu' (Correct answer)
- Only the first `a` element inside a div with class 'menu'
- All div elements that contain an `a` with class 'menu'
Correct answer: All `a` elements anywhere inside div elements with class 'menu'
The double-slash `//` before `a` means any descendant at any depth, not just direct children.
Question 3: Which CSS selector correctly matches an `<input>` element of type "text"?
- input[type='text'] (Correct answer)
- input.type='text'
- input#text
- input:text
Correct answer: input[type='text']
CSS attribute selectors use square bracket notation: `element[attribute='value']` to match specific attribute values.
Question 4: Which XPath axis selects the sibling element that immediately follows an element with id="first"?
- //*[@id='first']/following::*[1]
- //*[@id='first']/following-sibling::*[1] (Correct answer)
- //*[@id='first']/next-sibling::*
- //*[@id='first']+*
Correct answer: //*[@id='first']/following-sibling::*[1]
`following-sibling::*[1]` selects the first sibling that shares the same parent and appears after the context node.
Question 5: In Selenium WebDriver, which method returns all elements matching a locator as a `List<WebElement>`?
- driver.findElement()
- driver.getElementsBy()
- driver.findElements() (Correct answer)
- driver.getAllElements()
Correct answer: driver.findElements()
`driver.findElements()` (plural) returns a `List<WebElement>` containing all matching elements on the page.
Question 6: Which XPath function is used to find elements whose attribute value contains a specific substring?
- starts-with()
- substring()
- contains() (Correct answer)
- includes()
Correct answer: contains()
`contains(haystack, needle)` is the XPath function that returns true when the first string includes the second.
Question 7: What does the CSS selector `div > p` select when used with Selenium's `By.cssSelector()`?
- All p elements inside any div element at any depth
- All p elements that are direct children of a div element (Correct answer)
- All div elements that contain at least one p element
- The first p element inside each div element
Correct answer: All p elements that are direct children of a div element
The `>` combinator in CSS selects only direct children, so `div > p` matches `<p>` elements whose immediate parent is a `<div>`.
In CSS selector syntax used with Selenium, which symbol is used to target an element by its ID attribute?