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

二次信任 提交于 2020-07-08 00:49:09

问题


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";
  }
};

回答1:


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");



回答2:


You do not need the # when using getElementById. getElementById returns null if does not find the element. null does not have a property named type - therefore you get the error.

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


来源:https://stackoverflow.com/questions/33036800/why-does-document-getelementbyid-datepicker1-not-find-my-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!