Let's say I have several date inputs
, which I'd like to change color
after user input. With jQuery I could do:
$('input[type="date"]').on('change', function() {
var el = $(this).val();
if (el === '') {
$(this).css('color', '#9c9c9c');
} else {
$(this).css('color', '#000000');
}
})
input[type="date"] {
color: #9c9c9c;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" placeholder="MM/DD/YYYY">
<input type="date" placeholder="MM/DD/YYYY">
But, when I try to achieve the same with plain JS (document.querySelector()
or document.querySelectorAll().forEach()
), I'm unable to. I can only make the first input work with the document.querySelector()
approach:
var el = document.querySelector('input[type="date"]');
el ? el.onchange = function() {
if (this.value === '') {
this.style.color = '#9c9c9c';
} else {
this.style.color = '#000000';
}
} : "";
//tried also
/*document.querySelectorAll('input[type="date"]').forEach(function() {
this.onchange = function() {
if (this.value === '') {
this.style.color = '#9c9c9c';
} else {
this.style.color = '#000000';
}
}
});*/
input[type="date"] {
color: #9c9c9c;
}
<input type="date" placeholder="MM/DD/YYYY">
<input type="date" placeholder="MM/DD/YYYY">
Based on this excellent SO answer, I'm also using a ternary operator to check if the element exists in the DOM first, otherwise I'm getting error on pages where the inputs are not in the DOM.
How to achieve this with plain JS & avoiding null errors on non-existent DOM elements?