Newbie Spellweaver
- Joined
- Jun 9, 2010
- Messages
- 69
- Reaction score
- 11
<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>
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.
}
}
}
Thanks for this, going to use for a UserCP style system, I was thinking myql or cookies but javascript is easier xD (and i suck at it)
function getElementsByClass(className)
{
var elements = [];
var all = document.getElementsByTagName("*");
for(var i = 0; i < all.length; i++)
{
if(all[i].className == className)
{
elements.push(all[i]);
}
}
if(elements.length > 1)
{
this.count = elements.length;
return elements;
} else if(elements.length == 1)
{
return elements[0];
} else return 0;
}
var styledButtons = getElementsByClass('styledButtons');
// if only 1 is found, you can use it like this
styledButtons.style.color = red;
// if more than 1 is found
styledButtons[0].style.color = red;
styledButtons[1].style.color = blue;
// and you can return the numbers of elements with that class name found
document.write(styledButtons.count);
// for checking if more than 1 is found
if(styledButtons.count > 1) {}; // etc