Javascript isnt recognizing classes

Im trying various ways to trigger a transition, the simplest being the use of css pseudoclasses:


//leaving out default header stuff//
<head>
<style>
.item{
opacity:1;
-moz-transition: opacity 1s ease;
}
.item:hover {
opacity:0;
}
</style>
</head>
<body>
<img src="myimage.jpg" class="item" />
</body>

If i use js to make it trigger onclick instead of hover it works fine:


//leaving out default header stuff//
<head>
<style>
#item{
opacity:1;
-moz-transition: opacity 1s ease;
}
</style>
<script type="text/javascript">
function transition() {
            document.getElementById('item').style.opacity="0";
}
</script>
</head>
<body>
<img src="myimage.jpg" id="item" onclick="transition()" />
</body>

But if i replace the id’s with classes, it no longer works:


//leaving out default header stuff//
<head>
<style>
.item{
opacity:1;
-moz-transition: opacity 1s ease;
}
</style>
<script type="text/javascript">
function transition() {
            document.getElementsByClassName('item').style.opacity="0";
}
</script>
</head>
<body>
<img src="myimage.jpg" class="item" onclick="transition()" />
</body>

What am i doing wrong?

document.getElementsByClassName returns a collection through which you must iterate, applying the value to each element.

Just to note: document.getElementsByClassName() is not supported in IE8 or below.

So to get it to work in those browsers you need to test if getElementsByClassName exists and if not then include your own code to implement that functionality (by processing through all the tags and checking if the className attribute contains the specified class.