问题
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