fadedbee
fadedbee

Reputation: 44765

Getting the selected option in HTML without jQuery

I'm using the following function on each <option> to determine whether it is selected:

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

It works fine in jsdom in NodeJS, and it works for the selector :checked (on checkbox inputs) in the browser, but not for the selector :selected, which is odd.

I get the error (in Chrome):

Uncaught SyntaxError: Failed to execute 'matches' on 'Element': ':selected' is not a valid selector.

Upvotes: 4

Views: 3528

Answers (2)

alboforlizo
alboforlizo

Reputation: 361

I had "selected" to work with the following expression:

// check if any option has attribute selected
if(!dom_node.querySelectorAll("select option[selected]").length)
{
   dom_node.querySelector("select").value = "val";
}

Upvotes: 0

adeneo
adeneo

Reputation: 318232

The error message seems to be correct, :selected is not a valid selector, and even querySelector('option:selected') fails

The valid pseudo selectors are

: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

The correct psuedo class to use would be :checked, MDN says

The :checked CSS pseudo-class selector represents any radio (<input type="radio">), checkbox (<input type="checkbox">) or option (<option> in a <select>) element that is checked or toggled to an on state.

Upvotes: 11

Related Questions