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
As stated in the other answers, you cannot change pseudo-element styles inline. However, you can modify the CSS rule in the <style>
itself, and you don't need a browser support ing CSS variables for that. Access the stylesheet and either get the existing rule or insert your own, then play with its style declarations like you would with an element .style
:
const {sheet} = Object.assign(document.head.appendChild(document.createElement("style")), {type: "text/css" });const placeholderStyle = sheet.rules[sheet.insertRule("::placeholder {}")].style;placeholderStyle.color = "red";Object.assign(document.body.appendChild(document.createElement("input")), { type: "button", value: "Color!", onclick() { placeholderStyle.color = "#"+Math.round(Math.random()*0xFFF).toString(16).padStart("0",3);}});
<input placeholder="placeholder" />
There is another approach, but it's somewhat hacky: use JS to append more CSS to the end of the body. Browsers will override current CSS with the newest CSS, assuming the rules are identical.
function changeColor(toColor) { addCSS = document.createElement('style'); addCSS.innerHTML = "::placeholder { color: " + toColor + "; }"; document.body.append(addCSS);}
::placeholder { color: green; }
<input type="text" placeholder="placeholder"><button onclick="changeColor('red')">red</button><button onclick="changeColor('blue')">blue</button>