Selenium Web Element Locators & Selectors 2 — Questions and Answers
Question 1: Which of the following is a valid relative XPath expression in Selenium?
- /html/body/div/form/input
- //input[@id='username'] (Correct answer)
- input#username
- By.xpath("/input")
Correct answer: //input[@id='username']
Relative XPath starts with // and searches the entire document tree, making //input[@id='username'] flexible and valid.
Question 2: What does the XPath expression //button[contains(text(),'Submit')] select?
- Buttons with an attribute named 'Submit'
- Button elements whose visible text contains the substring 'Submit' (Correct answer)
- The first button element in the document
- Buttons with class 'Submit'
Correct answer: Button elements whose visible text contains the substring 'Submit'
The contains() function with text() matches button elements whose visible text includes 'Submit' as a substring.
Question 3: Which CSS selector selects only <p> elements that are DIRECT children of a <div>?
- div p
- div > p (Correct answer)
- div + p
- div ~ p
Correct answer: div > p
The > combinator selects only direct children, so div > p matches <p> elements immediately inside a <div>, not nested descendants.
Question 4: In XPath, what does the 'following-sibling' axis select?
- All ancestor elements of the current node
- All sibling elements that appear after the current node in the DOM (Correct answer)
- All sibling elements that appear before the current node
- The immediate parent element
Correct answer: All sibling elements that appear after the current node in the DOM
The following-sibling axis selects all siblings of the current node that appear after it in document order.
Question 5: Which CSS attribute selector matches elements whose attribute value STARTS WITH a specific string?
- [attr$='value']
- [attr*='value']
- [attr^='value'] (Correct answer)
- [attr~='value']
Correct answer: [attr^='value']
The ^= operator matches elements whose specified attribute value begins with the given string.
Question 6: What is the correct XPath expression to navigate to the parent element of a located <input> node?
- //input/child::*
- //input/parent::* (Correct answer)
- //input/ancestor
- //input/preceding::*
Correct answer: //input/parent::*
The parent:: axis in XPath selects the immediate parent node of the current element.
Question 7: Which CSS selector matches an element that has BOTH the class 'btn' AND the class 'primary'?
- .btn .primary
- .btn, .primary
- .btn.primary (Correct answer)
- #btn.primary
Correct answer: .btn.primary
Chaining class selectors without a space (.btn.primary) matches elements that have both classes simultaneously.
Which of the following is a valid relative XPath expression in Selenium?