How to update placeholder color using Javascript?

  • A+

I'm searching online and I didn't find anything. I'm trying to update the placeholder color of a textbox using javascript, but how can I do that? I have a color picker and the color is changing.

If I have something like this in my CSS, how can I update it?

::placeholder {   color: red; }
<input placeholder="placeholder" />

Is there a javascript command to edit this? Something like

document.getElementById('text').style.placeholderColor = newColor; 


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 variable are useful when it comes to modify pseudo-class/pseudo-element that you cannot access with JS such as :before/:after/::placeholer/::selection, etc. You simply define your property using a variable that you can easily update on the element.

Related :


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: