How to update placeholder color using Javascript?

Use CSS variables. You can also target only the needed element

function update() {
  document.querySelector('input[type=text]').style.setProperty("--c", "blue");
}
::placeholder {
  color: var(--c, red);
}
<input type="text" placeholder="I will be blue">
<input type="number" placeholder="I will remain red">
<button onclick="update()">change</button>

CSS variables are useful when it comes to modify pseudo elements that you cannot access with JS such as :before/:after/::placeholer/::selection, etc. You simply define your custom property that you can easily update on the main element and the pseudo element will inherit it.

Related : Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery

Leave a Comment