views:

47

answers:

2

I have the following function:

<script type="text/javascript">
function changeText(elem){
  var oldHTML = document.getElementById(elem).innerHTML;
  var newHTML = "<span style='color:red'>" + oldHTML + "</span>";
  document.getElementById(elem).innerHTML = newHTML;
 }

</script>

And the following HTML:

<table>
<tr>
<td id = "foo">bar</td>
</tr>
</table>

This throws a "unknown runtime error" (just in IE) which googling has since taught me that table elements are read-only in IE with innerHTML.

I've tried finding workarounds but they don't target my specific problem, which is just that I want to make the word "bar" red. I don't want to change the word "bar" to something else. Purely a color change.

Is there any way to do this without a complex and slow DOM function and without having to change any of the other HTML markup on the page? This is a table with a form in it, and if the surfer submits the form with an error, the "errored" fields should turn red. It has to be able to execute multiple times because it's possible for a surfer to mess up more than one field.

Thanks for any advice.

A: 

Why not just change the cell to have color:'red' :

var td = document.getElementById(elem);
td.style.color = 'red';
slebetman
lol...thanks that worked. Really had no idea it could be that simple..
ihatejavascript
A: 

Couple ways to go about it. Here are some quick ones to get you going -- or until someone else comes with a cleaner/better method.

I prefer the following: define an error class in css:

.errorHighlight { color:red;}

Then for the javascript:

function changeText(elem){ 
  document.getElementById(elem).className="errorHighlight"; 
} 
function changeTextBack(elem){ 
  document.getElementById(elem).className=""; 
} 

This assumes that you don't have any classes set already. If you do you may need to read the name, and append the error class with a space.

Again, there are a lot of ways to approach this and you want to pick the one best suited for your application.

WSkid