Search code examples
javascripthtmldomgetelementbyid

Why does `document.getElementById(“#datepicker1”)` not find my element?


I am trying to show / hide a text input based on the selection of a drop down list.

Here’s a JSFiddle to what I am trying to do.

When I get into the function, I get a TypeError: Cannot set property 'type' of null.

This is the code:

function showCustomDate(val) {
  console.log(val);
  if (val == 4) {
    var y = document.getElementById("#datepicker1");
    
    //console.log(y.type);
    y.type = "text";
  }
  else {
    var y = document.getElementById("#datepicker1");
    
    //console.log(y.type);
    y.type = "hidden";
  }
};

Solution

  • y is null, because the id of the element is probably datepicker1 and not #datepicker1

    var y = document.getElementById("#datepicker1");
    

    should be

    var y = document.getElementById("datepicker1");