What\'s the correct XPath syntax to check if an option
element is currently selected, or just to get the selected option
Short answer: it's not possible.
Longer answer: XPath can look at HTML attributes, but it can't look at DOM properties. Selecting an element in a
changes the
selected
property of the to
true
, and also changes the value
property of its parent element, but it doesn't affect the attributes of either, so it is invisible to XPath.
To find elements that have the
selected
attribute set, which is often how a page author might determine which option is initially selected, you can use //option[@selected]
. But this does not find the currently selected ; changes that the user makes to the selection are invisible to XPath. There's no guarantee it will even find the initially selected option, since it's possible that the page author didn't put the
selected
attribute on any elements and either let the browser select the first option by default or had some JavaScript select the initial option via the selected
property.
The multiple other answers here claiming that a selector like //option[@selected]
can detect selection changes made by the user after the page loads are simply completely wrong.
Of course, if you're able to use CSS selectors instead of XPath selectors, then option:checked will do the job.