changing td bgcolors on the fly

H

Holden Caulfield

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.backgroundColor = "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!!
 
M

Michael Winter

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.backgroundColor =
"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.className) {
// ...alter the colour value
cells.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
 
E

Evertjan.

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
 
@

@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.id=='cellchange')
D.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','getElementByName',
'getElementsByName','createElement','getElementByClass',
'getElementByClassName','getElementsByClassName');
T='<table>';
for(i=0;i<A.length;i++)
T += d(A);
T+= '</table>';
document.write(T);
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.id=='cellchange')
D.style.background='<? echo $color ?>';
}

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

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

--
**************************************************************
Stéphane MORIAUX : mailto:[email protected]
Aide aux Pages Perso (images & couleurs, formulaire, CHP, JS)
http://perso.wanadoo.fr/stephanePOINTmoriaux/internet/
**************************************************************
 
M

Michael Winter

@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.id=='cellchange')
D.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
 
M

Michael Winter

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.GetElementsByTagName('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.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.className) {
cells.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
 
L

Lasse Reichstein Nielsen

Michael Winter said:
I expect that you meant to do:

var d = table_id.getElementsByTagName('td');

more likely
var d = document.getElementById(table_id).getElementsByTagNam('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.className) {
cells.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
 
M

Michael Winter

Lasse Reichstein Nielsen wrote on 20 Dec 2003 at Sat, 20 Dec 2003
13:30:59 GMT:
more likely
var d =
document.getElementById(table_id).getElementsByTagNam('td');
The table_id is a string, not the table element node itself.

Was it? Oops.
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/author/dhtml/reference/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.className) {
cells.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.
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
 
L

Lasse Reichstein Nielsen

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

http://msdn.microsoft.com/workshop/author/dhtml/reference/collections/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
 
T

Thomas 'PointedEars' Lahn

Mateusz said:
<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
 
H

Holden Caulfield

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...
 
J

Jim Ley

Mateusz said:
<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.
 
T

Thomas 'PointedEars' Lahn

Jim said:
Thomas said:
Mateusz said:
<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
 
J

Jim Ley

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top