How to change colour of text when using document.getElementById("id").innerHTML
Asked Answered
P

3

6

I am trying to change the text of a span to something else when a particular event occurs. I am doing this as :

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

I want to display the same in a different colour. Any idea on how to do that? Much appreciated!

Peekaboo answered 30/7, 2015 at 8:59 Comment(1)
Do you have to change the color in the same line? You can simply use document.getElementById("usernameError").style.color function in the next line.Tocology
L
9

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

document.getElementById("usernameError").innerHTML = "<span style='color: red;'>**Message</span>";
Lissettelissi answered 30/7, 2015 at 9:1 Comment(0)
C
4

As you can find in the Mozilla Developer Network, you can use HTMLElement.style property to change any style on the element.

So you can do something like this to colour it in red:

 document.getElementById("usernameError").style.color = '#d00'
Chaffee answered 30/7, 2015 at 9:11 Comment(0)
N
1

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

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

Or working off Erics solution:

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

Then in your CSS:

.color-red{
    color: #F00;
}

You could obviously also add diff colours and attribute in a much more maintainable way like this.

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

Nematode answered 30/7, 2015 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.