Using a CSS Stylesheet with Javascript .innerHTML
Solution 1
As innerHTML suggests you can also add HTML. You could for instance add a span tag with a class that you style via CSS.
JS/CSS and HTML
document.getElementById('error-message').innerHTML = "<span class='error'>my error</span>";
.error {
color: red;
font-size: 24px;
}
<div id="error-message"></div>
Solution 2
Check this out , this answer should suffice to your needs:
document.getElementById("ID").innerHTML = "This is your error";
var sheet = document.createElement('style')
sheet.innerHTML = "div {color:red;overflow:hidden;}";
document.body.appendChild(sheet);
Add the below line to your span
#myspan{float:left;}
Working fiddle:http://jsfiddle.net/0z971bsn/
As you mentioned in the comments , to check for errors you can refer to the answer to this question How to get my forms' Javascript error function to cancel form submission and insert error message?
Jack Parker
By Day: Junior Java Developer By Night: Webmaster, Editor and Writer of cool cult film website. Started coding in 2008 after getting into IT with a tech support job, graduated with my comp sci B.S. in 2010, got my first real job in 2012.
Updated on February 12, 2020Comments
-
Jack Parker over 4 years
If I have a javascript function that loads an error using
document.getElementById("ID").innerHTML = "This is your error";
And I want to stylize it say change the text to a different color, and put the error into a different position, how would I go about doing that? I've been looking around, and cannot find any information.
-
Jack Parker over 9 yearsThat is precisely what I am looking for thank you. One final question that relates, since I have a number of errors on my form, for example name.error, job. error and so on, is there a catch all I can use so that they would all fit under one css tag?
-
Jack Parker over 9 yearsOK, one quick question if I may. What I have is in a span, at present it is underneath the field it is in reference too. If I wanted the error to appear in line next to the field what would I do? I've tried floating it, but that just keeps it underneath, but to the right.
-
m0bi5 over 9 years@JackParker ok , I edited my answer , check it out and let me know