chromosapiens chromosapiens - 5 months ago 10
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>
<html>
<head>
<title></title>
</head>
<body>
<input class="class" id="id" type="" name="" placeholder="placeholder text">
</body>
<style type="text/css">
.class::-moz-placeholder { /* Mozilla Firefox 19+ */
color: green;
}
.class2::-moz-placeholder {
color: red !important;
}
</style>
<script type="text/javascript">document.getElementById("id").className+="class2";</script>
</html>


Where is the mistake or which alternative does work?

Answer
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:

document.getElementById("id").classList.add("class2");