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!

+3


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>";

      

+3


source


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

to change any style on an element.

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



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

      

+2


source


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-red{
    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.

+1


source







All Articles