Categories
JavaScript Answers

How to update placeholder color using JavaScript?

Spread the love

Sometimes, we want to update placeholder color using JavaScript.

In this article, we’ll look at how to update placeholder color using JavaScript.

How to update placeholder color using JavaScript?

To update placeholder color using JavaScript, we can insert our own CSS rule into a style element.

For instance, we write:

<input type="text" placeholder="I will be blue">

to add an input.

Then we write:

const style = document.createElement("style")
style.type = "text/css"
const {
  sheet
} = document.head.appendChild(style)

const rule = sheet.insertRule("::placeholder {}")
const placeholderStyle = sheet.rules[rule].style;
placeholderStyle.color = "blue";

We write:

const style = document.createElement("style")
style.type = "text/css"
const {
  sheet
} = document.head.appendChild(style)

to add a new style element into the head element.

Then we write:

const rule = sheet.insertRule("::placeholder {}")
const placeholderStyle = sheet.rules[rule].style;

to insert a style rule for the placeholder and return it.

And then we set the placeholder’s color with:

placeholderStyle.color = "blue";

Now we should see that the placeholder’s color is blue.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *