Hey all, Sorry that this article is a bit late. I’ve been doing some major work and was too tired to write anything ![]()
I’ve actually started to learn the Internet beast JavaScript, and I think it’s about time I shared some knowledge I’ve gathered from problems I had when starting out.
The first of which is CSS styles. When starting out, one of the basic things I wanted to do was to change what the user sees dynamically. Not an easy task when there are few good examples online.
One of the first things you have to do is be able to find which element you want to change. For this you have to do a bit of “DOM” navigating, this scary thing is the Document Object Model, I don’t fully understand it yet myself, but from what little I do know, it reduces the HTML tags to objects. But that’s for another tutorial.
Here is an example basic HTML doc (with some inline JavaScript):
<html>
<head>
<title>Untitled Document</title>
<style type="text/css">
<!--
.CellClass
{
background-color:#CCC;
}
-->
</style>
<script type="text/javascript">
<!--
function doThis()
{
// code to go here
}
-->
</script>
</head>
<body onLoad="doThis()">
<table width="300" border="1" cellspacing="5" cellpadding="0">
<tr>
<td class="CellClass" id="Cell01"> </td>
<td class="CellClass" id="Cell02"> </td>
</tr>
</table>
</body>
</html>
OK, so we’ve got a table and a class of “CellClass” applied to the cells. Also we have a JS function that runs once the body of our page has loaded.
Now, let’s edit that with JS! (all code below will be placed where “// code to go here” is in our JavaScript)
First, lets get a reference to one of our cells:
document.getElementById('Cell01')
Then we browse through to the style:
document.getElementById('Cell01').style.backgroundColor = '#000000';
That’s it! Test your page in a browser and see your background colour change!
Please note that this does not effect the actual class, this simply applies a style that overrides the class.
If anybody knows a method of actually altering the CSS classes, I’m open to suggestions!
Stay cool,
-Bill



