Find CURRENTLY selected

后端 未结 4 1202
醉话见心
醉话见心 2021-01-04 06:42

What\'s the correct XPath syntax to check if an option element is currently selected, or just to get the selected option

4条回答
  •  离开以前
    2021-01-04 07:10

    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 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.

提交回复
热议问题