skip to Main Content

so I have an input and I was trying to change the color of the placeholder, in some websites I believe I see people are changing the placeholder color

I tried changing with elem.value but it doesn’t make any sense value and placeholder are two different things
even .placeholder and then style is not working as you can see below.
can’t find the way to do it
am I missing something?
here is my code:

 const elem = document.getElementById("myInput");
 elem.placeholder.style.color = "green";
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="new">
      <input type="text" id="myInput" placeholder="type here" />
    </div>
  </body>
</html>

2

Answers


  1. there’s an easy way with css, not javascript

    in css we have a pseudo-element called
    ::placeholder
    https://developer.mozilla.org/en-US/docs/Web/CSS/::placeholder

    as you may have guessed right now:

    #myInput::placeholder {
      color: green;
    }
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
      </head>
      <body>
        <div id="new">
          <input type="text" id="myInput" placeholder="type here" />
        </div>
      </body>
    </html>
    Login or Signup to reply.
  2. You can change 2 way HTML5 input placeholder color

    For example, below our HTML5 code:

    <input type="text" class="withOut" placeholder="Without placeholder color">
    <input type="text" class="withColor" placeholder="With placeholder color">
    
    1. Step one with only CSS

    As you can see I have added ID to change our input placeholder color.

    .withColor::placeholder {
      color: red;
      opacity: 1;
    }
    
    1. Step two. we can also change the placeholder color with JavaScript
    const ourChangeAbleInput = document.getElementsByClassName("withOut");
    ourChangeAbleInput.classList.add("withColor")
    

    That’s it 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search