Search code examples
javascripthtmldomdom-manipulation

JS can't find HTML select


I am trying to select the HTML select with javascript. But it seems not to be finding one. I have tried a few answers online to that problem, for example:

Wait for the window to fully load:

window.onload = function(){
    var opt = document.getElementsByName("productoptions");

    console.log(opt.options);
}

And tried to put js after the select element. And yes, I have checked the spelling many times. I would like to know, why that is happening. And every time it is throwing me in the console - undefined. Maybe you know the answer to that ;)

Current JS code:

var opt = document.getElementById("typeselector");
if(opt.value === "DVD")
{
    let furnitures = document.getElementsByClassName("furniture");
    for(let i = 0; i < furnitures.length; i++)
         furnitures[i].style.display = "none";
    let books = document.getElementsByClassName("book");
    for(let i = 0; i < books.length; i++)
         books[i].style.display = "none";
}

Part of the HTML code, responsible for HTML select part.

<div class="iRow">
     <div class="lclass"> 
          <label for="typeselector">Product Category</label> 
     </div>
     <div class="tclass"> 
          <select id="typeselector" name="productoptions">
               <option value="DVD">DVD-Disc</option>
               <option value="Book">Book</option>
               <option value="Furniture">Furniture</option>
          </select>
     </div>
</div>

Solution

  • document.getElementsByName returns array so use opt[0]

    window.onload = function(){
        var opt = document.getElementsByName("productoptions");
    
        console.log(opt[0].options);
    }
    <div class="iRow">
         <div class="lclass"> 
              <label for="typeselector">Product Category</label> 
         </div>
         <div class="tclass"> 
              <select id="typeselector" name="productoptions">
                   <option value="DVD">DVD-Disc</option>
                   <option value="Book">Book</option>
                   <option value="Furniture">Furniture</option>
              </select>
         </div>
    </div>