Hello, I am trying when simple code to add datepicker in javascript using below HTML and Javascript Code, but I am getting error "TypeError: Cannot read property 'classList' of null", how can I resolve it?
HTML/JS Code
<div class="row">
<div class="col-4">Min Age Date:</div>
<div class="col-8">
<input type="text" class="form-control" name="MinAgeDate"/>
<input type="checkbox" name="Active" id="Active" /> Active
</div>
</div><br />
<div class="row">
<div class="col-12">
<input type="checkbox" name="IncludeOnConfirmationEmail" id="IncludeOnConfirmationEmail" /> Include confirmation on Email
</div>
</div><br />
<script>
var minDate= document.getElementById("MinAgeDate");
minDate.classList.add('datePickerClass');
</script>
Thanks.
This error occurs when you are trying to following things:
classList
property on a null value, a DOM element that doesn't exist.
So, as per your above code, you are using "name" attribute but not "id" attribute for 'MinAgeDate
', here is the error explanation:
var minDate= document.getElementById("MinAgeDate"); //no element with ID 'MinAgeDate' exists in HTML
console.log(minDate); // null
//you will get error here
minDate.classList.add('datePickerClass');
Either add the attribute id to your input or change getElementById to getElementsByName.
I will add id attribute to input element, so your HTML will be like this
<input type="text" class="form-control" name="MinAgeDate" id="MinAgeDate" />
That's it, you are done.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly