David David - 5 months ago 14
CSS Question

Assigning CSS style to variable in JavaScript

I am writing a simple JavaScript function that takes a td (table cell) and either gives it a red border style or turns this off. The code is:

function doStuff(theCell)
{
var highlight = "2px solid rgb(255, 0, 0)";
if(borderStyle==highlight)
{
theCell.style.border="";
}
else
{
theCell.style.border=highlight;
}
}


This works fine. However to try to make the code cleaner I tried to replace the css border style by a variable (declared just below the first one):

var borderStyle = theCell.style.border;


This works OK when I use it in the equality comparison, but not when I put it in the style assignation in the ‘else’ clause.

I must be trying to do something very foolish. Could anyone explain.

Answer

Javascript does not create reference to the object if you write code such as var borderStyle = theCell.style.border;. Here a copy of only the value of border is assigned to borderStyle. The object which is theCell remained unharmed at its place. No reference is created to it.

Comments