How to change text color when using document.getElementById ("id"). InnerHTML

I am trying to change the text of a span to something else when a specific event occurs. I do it like:

document.getElementById("usernameError").innerHTML = "**Message";


I want to display the same in a different color. Any idea on how to do this? We really appreciate it!


source to share

3 answers

You can always just put a message in the gap and put a style attribute on it. This should do it:

document.getElementById("usernameError").innerHTML = "<span style='color: red;'>**Message</span>";




As you can find on the Mozilla Developer Network , you can use a property

to change any style on an element.

So, you can do something like this to color it red:

 document.getElementById("usernameError").style.color = '#d00'




A more robust and reusable solution would probably be to add a class to the current or span element depending on your requirements:

document.getElementById("usernameError").className = "color-red";


Or try Erics' solution:

document.getElementById("usernameError").innerHTML = "<span class='color-red'>**Message</span>";


Then in your CSS:

    color: #F00;


You can also add colors and diff attributes in a much more convenient way.

NOTE: className Returns a string representing the class, or a space-separated list of classes, of the element.



All Articles