PDA

View Full Version : JS Add style attribute to table cell



NeoDreamer
December 27th, 2008, 01:06 AM
I wrote code to put a border around all cells in a specific table column. I used "firstChild" and "nextSibling" in a double nested while loop to locate all of the cells in that column. Now when I did:



tableCell.setAttribute("style", "border = 1px solid #BFD44B");


I get the error in Firebug: tableCell.setAttribute is not a function. I verified that tableCell is a "HTMLTableCellElement" by alerting it. I'm completely new to JS, so.....

littleking84
December 27th, 2008, 04:08 AM
do you have this anywhere above that line in the script?


var tableCell = document.getElementById('tableCell');


I'm assuming you have tableCell as either a id or class

NeoDreamer
December 27th, 2008, 01:14 PM
No, the table is completely unlabeled. "cellNum" is defined by user input and this code will attempt to put a border around all cells in column # cellNum in the table.



<table id="myAccountGroupsTableBody">
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>




var tableBody = document.getElementById("myAccountGroupsTableBody");
var tableRow = tableBody.firstChild;
var tableCell = null;
var curCell = 0;

while(tableRow != tableBody.lastChild )
{
tableCell = tableRow.firstChild;

curCell = 0;

while(tableCell != tableRow.lastChild)
{
if(curCell == cellNum)
tableCell.setAttribute("style", "border = 1px solid #BFD44B");

curCell++;

tableCell = tableCell.nextSibling;
}

tableRow = tableRow.nextSibling;
}