JavaScript and CSS Classes

For years I have known that one can muck with an object's style using JavaScript and the STYLE attribute of a DOM object. However, I have found this to often be frustrating as the naming convention of the elements is not always the same as CSS. I wondered for a while if we could simply apply a pre-existing CSS Class to an element.

Well it turns out that you can apply a CSS class to a DOM object via JavaScript, via the className attribute.

Here's an example:

<input type="text" id="QA1" name="QA1" value="" class="Answer" />

<InvalidTag language="javascript" type="text/javascript">
// function declaration ...
var QA1 = document.getElementById('QA1');

if(QA1.value.length == 0) {
QA1.className = "AnswerRequired";
// More actions ....
}
</script>

Since I found how to do this a few weeks ago, it has made adding some visual spark to forms in particular, a bit easier. Enjoy!

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Be sure to replace the "InvalidTag" in the example with "Script" -- my host has apparently enabled ColdFusion script protection which changed the tag value before presenting it.
# Posted By Ted | 10/27/09 1:13 PM
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.