- Joined
- Jun 9, 2010
- Messages
- 69
- Reaction score
- 11
Hi guys, this is just a little tutorial on how to select elements by their class. It won't work like document.getElementsByClass(class). I'm going to show you my example and then break it down.
Explanation: The example is a table with 5 rows and columns, each table cell is labeled like X and Y coordinates. As you can see there are table cells with a class "colorful". When the button is clicked, it will trigger the JavaScript function which changes the background color of all elements with the class "colorful" (or the supplied class).
The HTML:
The JavaScript Explanation:
Hope this helps! I can't upload attachments, why? Is it my rank? :laugh:
Explanation: The example is a table with 5 rows and columns, each table cell is labeled like X and Y coordinates. As you can see there are table cells with a class "colorful". When the button is clicked, it will trigger the JavaScript function which changes the background color of all elements with the class "colorful" (or the supplied class).
The HTML:
Code:
<html>
<head>
<title>Javascript - Get Elements By Class</title>
<link href="style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<script type="text/javascript">
function changeColor(color, Class)
{
var all = document.getElementsByTagName('*');
for(var i = 0; i < all.length; i++)
{
if(all[i].className == Class)
{
all[i].style.backgroundColor = color;
}
}
}
</script>
<table border="1" id="content">
<tr>
<td class="colorful">1,1</td>
<td>2,1</td>
<td>3,1</td>
<td>4,1</td>
<td class="colorful">5,1</td>
</tr>
<tr>
<td>1,2</td>
<td class="colorful">2,2</td>
<td>3,2</td>
<td class="colorful">4,2</td>
<td>5,2</td>
</tr>
<tr>
<td>1,3</td>
<td>2,3</td>
<td class="colorful">3,3</td>
<td>4,3</td>
<td>5,3</td>
</tr>
<tr>
<td>1,4</td>
<td class="colorful">2,4</td>
<td>3,4</td>
<td class="colorful">4,4</td>
<td>5,4</td>
</tr>
<tr>
<td class="colorful">1,1</td>
<td>2,1</td>
<td>3,1</td>
<td>4,1</td>
<td class="colorful">5,1</td>
</tr>
<tr>
<td colspan="5"><button onclick="javascript:changeColor('red','colorful');">Red</button> or <button onclick="javascript:changeColor('blue','colorful');">Blue</button></td>
</tr>
</body>
</html>
The JavaScript Explanation:
PHP:
function changeColor(color, Class)
{
var all = document.getElementsByTagName('*'); //Gets all elements in the current document.
for(var i = 0; i < all.length; i++) //The variable "i" is like the number of elements, or the size of the array "all".
{
if(all[i].className == Class) //If element number "i" has the class supplied in the function..
{
all[i].style.backgroundColor = color; //Change that element's background color to the supplied color.
}
}
}
Hope this helps! I can't upload attachments, why? Is it my rank? :laugh: