Normally in CSS you would use the ::placeholder
selector to modify placeholder color. In JavaScript, you can’t really modify CSS pseudo selectors, so you’ll have to assign a specific class to each placeholder color like so:
var input = document.getElementById("searchAdress");
function validate(){
var value = input.value;
if(value.length>0){
//Valid
input.value="";
input.placeholder="Got it";
clearOtherClasses(input);
input.classList.add("green");
}else{
//Invalid
input.value="";
input.placeholder="Nope";
clearOtherClasses(input);
input.classList.add("red");
}
}
function clearOtherClasses(element){
element.className="";
}
.green::placeholder{
color:green;
}
.red::placeholder{
color:red;
}
<input type="text" id="searchAdress" placeholder="Type an adress, city or country"><button onclick="validate()">validate</button>
<hr>
Enter nothing to toggle red placeholder text. Enter something to toggle green.
The function clearOtherClasses()
is used to prevent conflicting color classes (e.g, an input has both the green
class and the red
class).