Which element would this selector choose?

I have a form element as follow

<form name="selectForm">
    <label for="musicTypes">Choose some music types, then click the button below:</label>
    <select id="musicTypes" name="musicTypes" multiple="multiple">
      <option selected="selected">R&B</option>
      <option>New Age</option>
  <p><input id="btn" type="button" value="How many are selected?" /></p>

The output of document.selectForm.musicTypes is the entire block within select tags . What does the dot(.) before musicTypes mean? Aren’t elements with an id selected using the # ?

It’s JavaScript, not CSS. It represents the document as an object, and IDs are global variables (Seems name attributes are also global variables if that’s working, which I wasn’t aware of). So looks like

  window: {
    document: {
      selectForm: {
        musicTypes: {
          // the DOM node with the ID #music-types

Note I wouldn’t rely on this behaviour (being able to select them like that), I would always try to use eg document.querySelector("#music-types") rather than assuming that you can just select using normal object access notation, which is likely to lead to errors.


Yea, I missed this part about the global window . And I have been using querySelectors myself all along. This is actually an example lifted from the MDN documentation. Thanks for pointing this out.

1 Like