chromosapiens chromosapiens - 1 year ago 111
Javascript Question

change style of input placeholder with java script

I tried to change the color of the placeholder by adding a new class, so that the color property is overwritten. However, it does not seem to work.
Following code is intended to change the placeholder color from green to red, however it is changed from green to default black/gray.

<!DOCTYPE html>
<input class="class" id="id" type="" name="" placeholder="placeholder text">
<style type="text/css">
.class::-moz-placeholder { /* Mozilla Firefox 19+ */
color: green;
.class2::-moz-placeholder {
color: red !important;
<script type="text/javascript">document.getElementById("id").className+="class2";</script>

Where is the mistake or which alternative does work?

Answer Source
document.getElementById("id").className += "class2";

turns the class name into "classclass2". Because there is no corresponding class classclass2 in your CSS, this element is ignored. Add a space before the new class name:

document.getElementById("id").className += " class2";

or use the more modern classList approach:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download