Selenium Web Element Locators & Selectors 1 — Questions and Answers
Question 1: Which Selenium locator strategy is generally fastest and most reliable when an element has a unique ID attribute?
- By.name()
- By.xpath()
- By.id() (Correct answer)
- By.cssSelector()
Correct answer: By.id()
By.id() directly maps to the HTML 'id' attribute and is the most performant locator when IDs are unique and stable.
Question 2: What does driver.findElements() return when no elements match the given locator?
- null
- Throws NoSuchElementException
- An empty List<WebElement> (Correct answer)
- A WebElement with no properties
Correct answer: An empty List<WebElement>
findElements() always returns a List<WebElement> — an empty list when nothing matches, never null or an exception.
Question 3: Which Selenium locator strategy finds an anchor element by its complete visible text?
- By.tagName("a")
- By.partialLinkText()
- By.linkText() (Correct answer)
- By.name()
Correct answer: By.linkText()
By.linkText() matches the full visible text of an anchor (<a>) element exactly.
Question 4: What is the correct Selenium syntax to locate an element by its CSS class name?
- driver.findElement(By.id("myClass"))
- driver.findElement(By.className("myClass")) (Correct answer)
- driver.findElement(By.name("myClass"))
- driver.findElement(By.tagName("myClass"))
Correct answer: driver.findElement(By.className("myClass"))
By.className() is the Selenium locator strategy designed specifically to find elements by their CSS class attribute.
Question 5: Which Selenium method throws a NoSuchElementException when the target element is not present in the DOM?
- driver.findElements()
- driver.findElement() (Correct answer)
- driver.waitFor()
- driver.querySelector()
Correct answer: driver.findElement()
driver.findElement() throws NoSuchElementException immediately if no matching element is found, unlike findElements() which returns an empty list.
Question 6: Which locator strategy would you use to match a hyperlink whose text only partially matches the expected string?
- By.linkText()
- By.partialLinkText() (Correct answer)
- By.xpath()
- By.id()
Correct answer: By.partialLinkText()
By.partialLinkText() allows matching a substring of the anchor element's visible text without requiring the full string.
Question 7: What does driver.findElement(By.tagName("input")) return when multiple <input> elements exist on a page?
- All input elements as a list
- null
- The first matching input element in DOM order (Correct answer)
- Throws NoSuchElementException
Correct answer: The first matching input element in DOM order
findElement() always returns the first matching element encountered in DOM order when multiple matches exist.
Which Selenium locator strategy is generally fastest and most reliable when an element has a unique ID attribute?