PDA

View Full Version : onclick add a classname to a TAG


sugar2
05-18-2005, 02:48 AM
im trying to add a class name in a exsisting TD tag of a HTML table.

this code doesnt print any errors but dont add the class either...

<SCRIPT>
function changeclass() {
var NAME = document.getElementsByTagName("TD")
NAME.className="items"
}
</SCRIPT>

<a href="#" onclick="changeclass();">TEST</a>

and this is my table sample wich have no class asigned, it is waiting for the script who is supposed will add it a neww class

<style>
TD.items {COLOR: 000;}
TD.items A:link {COLOR: blue; font-weight: bold;}
TD.items A:visited {COLOR: blue; font-weight: bold;}
TD.items A:active {COLOR: blue; font-weight: bold;}
TD.items A:hover {COLOR: #505C6D; font-weight: bold;}
</style>
<table>
<tr>
<td><a href="http://somewhere.com"><b>my custom text</a></td>
</tr>
</table>

any help will be apreciated

thanks

Harry Armadillo
05-18-2005, 03:03 AM
The key is document.getElementsByTagName(...). Elements, plural. It returns a collection, essentially an array, of elements. Try NAME[0].className="items"

sugar2
05-18-2005, 06:51 PM
thanks for advising...
i did it:...
<SCRIPT>
function changeclass() {
var NAME = document.getElementsByTagName("TD")
NAME[0].className="items"
}
</SCRIPT>

<a href="#" onclick="changeclass();">TEST</a>

still no work
could the NAME var should be a matrix??

Harry Armadillo
05-18-2005, 07:06 PM
Try <input type='button' value='Test!' onclick='changeclass()'>

sugar2
05-18-2005, 11:44 PM
[code]
<BODY onLoad="javascript:changeclass();">

<SCRIPT>
function changeclass() {
var name=document.getElementsByTagName('td');
for (var i=0; i<name.length; i++)
{
name[i].className='items';
}
}
</SCRIPT>

html blabla tables blabla
</body> [code]

the issue was that document.getElementsByTagName returns a matrix, no a single value
thnaks for the advice!

sugar2
05-19-2005, 05:52 PM
wrong value
what you mean?

i belive the last code works like a charm!...