By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,814 Members | 2,162 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,814 IT Pros & Developers. It's quick & easy.

changing td bgcolors on the fly

P: n/a
Hi there,
for IE 5+ I need to be able to change certain TD tags´ background
colors, and can´t figure out how to do it...

For instance, in a table with 25 cells, somewhere between 5 or 10 will
need the bgcolor to change at the same time when a user clicks a
button. Right now only one changes when I use something like this...

document.getElementById(´cellchange´).style.backgr oundColor = "FFFFFF"
** (Note, this is not the EXACT code, I am typing from memory... but
it is SOMEthing like thw above...)

where a few td cells have an "id=cellchange" in there tag. I need ALL
of the ones with that ID to change!

Is there a getElementByClass, for multiple similar elements?

Thanks!

Holden
PS: The cells to change are set through ASP and are different for
every user.
PPS: It is an intranet app and ONLY HAS TO WORK WITH IE 5 and later!!
Jul 20 '05 #1
Share this Question
Share on Google+
14 Replies


P: n/a
Holden Caulfield wrote on 13 Dec 2003 at Sat, 13 Dec 2003 22:14:32
GMT:
Hi there,
for IE 5+ I need to be able to change certain TD tags´
background colors, and can´t figure out how to do it...

For instance, in a table with 25 cells, somewhere between 5 or
10 will need the bgcolor to change at the same time when a user
clicks a button. Right now only one changes when I use
something like this...

document.getElementById(´cellchange´).style.backgr oundColor =
"FFFFFF" ** (Note, this is not the EXACT code, I am typing from
memory... but it is SOMEthing like thw above...)

where a few td cells have an "id=cellchange" in there tag. I
need ALL of the ones with that ID to change!
An ID /must/ be unique in a document. You /cannot/ give multiple
elements the same ID.
Is there a getElementByClass, for multiple similar elements?


You could assign the cells a common class name then use
document.getElementsByTagName() to retrieve all table cells in the
document. You can then loop through the collection returned and
search for those elements that match that class ('cellchange',
below):

// Check that browser supports DOM method
if (document.getElementsByTagName) {
// Get table cells in document
var cells = document.getElementsByTagName('td');
var numCells = cells.length;

// Loop through elements returned
for (var i = 0; i < numCells; ++i) {
// If cell should be changed (matching class)...
if ('cellchange' == cells[i].className) {
// ...alter the colour value
cells[i].style.backgroundColor = '#FFFFFF';
}
}
}

I haven't tried this, but from the looks of the DHTML reference in
Microsoft's MSDN Library, it should work. Just a reminder: colour
(RGB) values must have a hash (#) symbol in front of them.

Mike

--
Michael Winter
M.******@blueyonder.co.invalid (replace ".invalid" with ".uk")
Jul 20 '05 #2

P: n/a
Holden Caulfield wrote on 13 dec 2003 in
comp.lang.javascript:
PS: The cells to change are set through ASP and are
different for every user.
PPS: It is an intranet app and ONLY HAS TO WORK WITH IE 5
and later!!


With serverside asp-vbs and clientside css classes you can
set what class belongs to what <td>:

<%
if user="Holden" then c17="clGreen" else c17="clRed"
if b=true then c18="clGreen" else c18="clRed"
if c17="clRed" then c19="clGreen" else c19="clRed"
if user<>"Holden" then c20="clGreen" else c20="clRed"
if ... then c21="clGreen" else c21="clRed"
%>
<style>
..clGreen {color:green;background-color:black;}
..clRed {color:red;background-color:navy;}
</style>

<td class='<%=c17 %>'>.....
<td class='<%=c18 %>'>.....
<td class='<%=c19 %>'>.....
<td class='<%=c20 %>'>.....
<td class='<%=c21 %>'>.....

with clientside js you can change the values of each class:

<script>
myRules = document.styleSheets[0].rules;
// if the style declaration is the first one

function changeClGreenBg(x) {
myRules[0].style.backgroundColor = x;
// first rule is clGreen
}
</script>

<button onclick="changeClGreenBg('red')">
black bgs to become red</button>

Not tested! Believed to be good, perhaps debuging is in
order.
Only for IE, as NS wants cssRules, nor rules

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jul 20 '05 #3

P: n/a
@SM
Holden Caulfield a ecrit :
Hi there,
for IE 5+ I need to be able to change certain TD tags´ background
colors, and can´t figure out how to do it...

where a few td cells have an "id=cellchange" in there tag. I need ALL
of the ones with that ID to change!
function chang(){
D = document.getElementsByTagName('td');
for(i=0;i<D.length;i++)
if(D[i].id=='cellchange')
D[i].style.background='red';
}
Is there a getElementByClass, for multiple similar elements?
no, I don't think so

do a test with that :

<html><script type="text/javascript">
function d(e){
f='document.'+e;
e=eval('document.'+e);
if(e) {c='green'; r='YES';} else {c='yellow'; r='NO';}
t ='<tr><th>'+f+'</th><td bgcolor="'+c+'">'+r+'</td></tr>';
return t;
}
t = '';
A = new Array('getElementById','getElementByTagName',
'getElementByTags','getElementByTagsName',
'getElementByTagsNames','getElementsByTag',
'getElementsByTagName','getElementsById','getEleme ntByName',
'getElementsByName','createElement','getElementByC lass',
'getElementByClassName','getElementsByClassName');
T='<table>';
for(i=0;i<A.length;i++)
T += d(A[i]);
T+= '</table>';
document.write(T);
</script></html>
Thanks!

Holden
PS: The cells to change are set through ASP and are different for
every user.
and ?? is it important ?
PPS: It is an intranet app and ONLY HAS TO WORK WITH IE 5 and later!!


that does on mine (Mac IE 5.0)

variantes :
---- 1 ----
function phpchang(){
D = document.getElementsByTagName('td');
for(i=0;i<D.length;i++)
if(D[i].id=='cellchange')
D[i].style.background='<? echo $color ?>';
}

----- 2 -----
function tdBac(color){
D = document.getElementsByTagName('td');
for(i=0;i<D.length;i++)
if(D[i].id=='cellchange')
D[i].style.background=color;
}

<a href="javascript:tdBac('yellow');"> Yellow </a>
<a href="javascript:tdBac('#333');"> Grey </a>

--
************************************************** ************
Stéphane MORIAUX : mailto:st*********************@wanadoo.fr
Aide aux Pages Perso (images & couleurs, formulaire, CHP, JS)
http://perso.wanadoo.fr/stephanePOINTmoriaux/internet/
************************************************** ************
Jul 20 '05 #4

P: n/a
@SM wrote on 13 Dec 2003 at Sat, 13 Dec 2003 23:57:55 GMT:
function chang(){
D = document.getElementsByTagName('td');
for(i=0;i<D.length;i++)
if(D[i].id=='cellchange')
D[i].style.background='red';
}


Pretty much what I said, except that you're ignoring the fact that
only /one/ instance of an ID can appear in a document. Even if IE
allows it, it's still wrong and there's an alternative solution
(mine). I haven't tested it, but it should work if Microsoft conform
to their own documentation.

Mike

--
Michael Winter
M.******@blueyonder.co.invalid (replace ".invalid" with ".uk")
Jul 20 '05 #5

P: n/a
function chang(table_id, bgc){
d = document.getElementsById(table_id.GetElementsByTag Name('td');
for(i=0;i<d.length;i++) d[i].style.background=bgc;
}

<table id="sth">...</table>

<script type="text/javascript" language="javascript"> <!-- <![CDATA[
chang( "sth", "red");
// ]]> -->
</script>

morson


Jul 20 '05 #6

P: n/a
Mateusz wrote on 20 Dec 2003 at Sat, 20 Dec 2003 10:21:11 GMT:
function chang(table_id, bgc){
d = document.getElementsById(table_id.GetElementsByTag Name('td');
This is a syntax error:

1) The document object doesn't have the method, getElementsById().
2) The correct method, getElementById(), takes a single String
argument that contains the ID of the element.
3) The table object doesn't have the method, GetElementsByTagName().
4) The correct method, getElementsByTagName(), returns a collection
(in your code) of table cells which, as already mentioned, is not
the correct type for getElementById().
5) You have a mismatching bracket; no closing ')'.

From a good practice point-of-view, you should declare 'd' above and
'i' below using the var keyword (so they're in local scope). Finally,
you should test that the methods called are available before using
them.

I expect that you meant to do:

var d = table_id.getElementsByTagName('td');
for(i=0;i<d.length;i++) d[i].style.background=bgc;
}

<table id="sth">...</table>

<script type="text/javascript" language="javascript"> <!-- <![CDATA[
There's no need to use the language attribute.
chang( "sth", "red");
// ]]> -->
</script>


One last point, the OP wanted to change the background of specific
cells, not the entire table. If your first line is used with my
solution, it will produce a much more efficient method:

// Changes the background colour of table cells
//
// table - the table object to be re-coloured
// cellClass - a string with the class name that changeable cells
// should have
// colour - a string containing the new background colour of the
// form '#rrggbb'
//
function changeCells( table, cellClass, colour ) {
var cells = null;

if (table.getElementsByTagName) {
cells = table.getElementsByTagName('td');
} else if (table.cells) {
cells = table.cells;
}

if (cells) {
var numCells = cells.length;

for (var i = 0; i < numCells; ++i) {
if (cellClass == cells[i].className) {
cells[i].style.backgroundColor = colour;
}
}
}
}

One thing I didn't get around to checking was if the style access
above works on non-IE supporting browsers (NS and Mozilla, for
example). I haven't figured out the DOM Level 2 Style Spec. yet, so if
someone can provide an example, I'd be grateful.

Mike

--
Michael Winter
M.******@blueyonder.co.invalid (replace ".invalid" with ".uk")
Jul 20 '05 #7

P: n/a
Michael Winter <M.******@blueyonder.co.invalid> writes:
I expect that you meant to do:

var d = table_id.getElementsByTagName('td');
more likely
var d = document.getElementById(table_id).getElementsByTag Nam('td');
The table_id is a string, not the table element node itself.

if (table.getElementsByTagName) {
cells = table.getElementsByTagName('td');
} else if (table.cells) {
Which browser is this? The DOM allows "table.rows", where each row
contains a "cells" property.

For IE 4, you can use
table.all.tags("td")
if (cellClass == cells[i].className) {
cells[i].style.backgroundColor = colour; One thing I didn't get around to checking was if the style access
above works on non-IE supporting browsers (NS and Mozilla, for
example).
It's absolutely correct.
I haven't figured out the DOM Level 2 Style Spec. yet, so if
someone can provide an example, I'd be grateful.


elemNode.style.backgroundColor = "white"
is a fine example of DOM 2 Style CSS.
Browsers let element nodes implement the ElementCSSInlineStyle interface,
so they have a "style" property that is a CSSStyleDeclaration. That
again can be accessed using the interface of CSSStyleDeclaration, with
normal object property access notation being equivalent to the "item"
method.
Good lcuk.
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #8

P: n/a
Lasse Reichstein Nielsen wrote on 20 Dec 2003 at Sat, 20 Dec 2003
13:30:59 GMT:
Michael Winter <M.******@blueyonder.co.invalid> writes:
I expect that you meant to do:

var d = table_id.getElementsByTagName('td');
more likely
var d =
document.getElementById(table_id).getElementsByTag Nam('td');
The table_id is a string, not the table element node itself.


Was it? Oops.
if (table.getElementsByTagName) {
cells = table.getElementsByTagName('td');
} else if (table.cells) {


Which browser is this? The DOM allows "table.rows", where each row
contains a "cells" property.


table.cells is directly from Microsoft's DHTML reference (my
newsreader might destroy this URL):

http://msdn.microsoft.com/workshop/a...e/collections/
cells.asp

If 'object' in the first usage presented is a table object, all of the
cells in the table are returned. It doesn't state when it was
introduced.
For IE 4, you can use
table.all.tags("td")


That might be a necessary replacement for the second branch.
if (cellClass == cells[i].className) {
cells[i].style.backgroundColor = colour;

One thing I didn't get around to checking was if the style access
above works on non-IE supporting browsers (NS and Mozilla, for
example).


It's absolutely correct.


Though I forgot to add a check to see if the style property was
implemented.
I haven't figured out the DOM Level 2 Style Spec. yet, so if
someone can provide an example, I'd be grateful.


elemNode.style.backgroundColor = "white"
is a fine example of DOM 2 Style CSS.
Browsers let element nodes implement the ElementCSSInlineStyle
interface, so they have a "style" property that is a
CSSStyleDeclaration. That again can be accessed using the
interface of CSSStyleDeclaration, with normal object property
access notation being equivalent to the "item" method.


Thank you. As I've had no need to modify style properties, or in fact
use any Level 2 DOM, I wasn't sure what the correct syntax was. I only
knew that MS' DHTML supports it (from IE 4 onwards).

Mike

--
Michael Winter
M.******@blueyonder.co.invalid (replace ".invalid" with ".uk")
Jul 20 '05 #9

P: n/a
Michael Winter <M.******@blueyonder.co.invalid> writes:
table.cells is directly from Microsoft's DHTML reference (my
newsreader might destroy this URL):

http://msdn.microsoft.com/workshop/a...ions/cells.asp
I see. It is slightly misleading. They say the collection is defined in he
W3C DOM level 1. That is partially correct, but W3C DOM 1 only puts it as
a property of the HTMLTableRowElement, not on HTMLTableElement.
If 'object' in the first usage presented is a table object, all of the
cells in the table are returned. It doesn't state when it was
introduced.


So that is non-W3C DOM behavior.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #10

P: n/a
Mateusz wrote:
<script type="text/javascript" language="javascript"> <!-- <![CDATA[
[...]
// ]]> -->
</script>


Using an XML parser the above should result in an `<script/>'.
Using a tag soup parser it depends on how much tag soup it eats.
PointedEars
Jul 20 '05 #11

P: n/a
Just wanted to say thanks for the responses! Especially Mike
Winters´, whose code worked perfectly!

Thanks again!

Holden
PS: Sorry for the late reply, I am travelling in Latin America and
connections are, er, erratic...
Jul 20 '05 #12

P: n/a
On Sat, 20 Dec 2003 23:53:08 +0100, Thomas 'PointedEars' Lahn
<Po*********@web.de> wrote:
Mateusz wrote:
<script type="text/javascript" language="javascript"> <!-- <![CDATA[
[...]
// ]]> -->
</script>


Using an XML parser the above should result in an `<script/>'.


Surely not! There's 2 whitespace nodes and a comment inside the
script element... :-)

Jim.
--
comp.lang.javascript FAQ - http://jibbering.com/faq/

Jul 20 '05 #13

P: n/a
Jim Ley wrote:
Thomas 'PointedEars' Lahn wrote:
Mateusz wrote:
<script type="text/javascript" language="javascript"> <!-- <![CDATA[
[...]
// ]]> -->
</script>
Using an XML parser the above should result in an `<script/>'.


Surely not! There's 2 whitespace nodes


True :)
and a comment inside the script element... :-)


I wrote: `should *result* in'. After parsing, the comment is no more
since it is required for an XML parser to remove all comments *before*
building the parse tree.
PointedEars
Jul 20 '05 #14

P: n/a
On Mon, 22 Dec 2003 17:21:30 +0100, Thomas 'PointedEars' Lahn
<Po*********@web.de> wrote:
Jim Ley wrote:
and a comment inside the script element... :-)


I wrote: `should *result* in'. After parsing, the comment is no more
since it is required for an XML parser to remove all comments *before*
building the parse tree.


I understood the removal of comments was optional, not required that
they do that.

Jim.
--
comp.lang.javascript FAQ - http://jibbering.com/faq/

Jul 20 '05 #15

This discussion thread is closed

Replies have been disabled for this discussion.