在没有jQuery的情况下在HTML中获取所选选项

fad*_*bee 2 javascript dom node.js

我在每个上使用以下函数<option>来确定它是否被选中:

var _matches = function(el, selector) {
  var fn = el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector;
  return fn.call(el, selector);
};
Run Code Online (Sandbox Code Playgroud)

jsdom在NodeJS中运行良好,它适用于:checked 浏览器中的选择器(在复选框输入上),但不适用于:selected奇数的选择器.

我收到错误(在Chrome中):

未捕获的SyntaxError:无法在'Element'上执行'matches':':selected'不是有效的选择器.

ade*_*neo 5

错误消息似乎是正确的,:selected不是有效的选择器,甚至querySelector('option:selected')失败

有效的伪选择

:active
:checked
:default
:dir()
:disabled
:empty
:enabled
:first
:first-child
:first-of-type
:fullscreen
:focus
:hover
:indeterminate
:in-range
:invalid
:lang()
:last-child
:last-of-type
:left
:link
:not()
:nth-child()
:nth-last-child()
:nth-last-of-type()
:nth-of-type()
:only-child
:only-of-type
:optional
:out-of-range
:read-only
:read-write
:required
:right
:root
:scope
:target
:valid
:visited
Run Code Online (Sandbox Code Playgroud)

MDN说:checked,要使用正确的伪类

:checkedCSS伪类选择表示任何无线电(<input type="radio">),复选框(<input type="checkbox">)或选项(<option> 在一个<select>),其被选中或切换到导通状态元素.