Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is document.getElementById('tableId').innerHTML not working in IE8?

Tags:

I modify document.getElementById('').innerHTML with Java Script in a page. It's working fine in Firefox, but not IE8. Please see below for more details:

HTML Code:

<table>   <tr id="abc">      <td id="ccc" style="color:red;">ccc</td>   </tr> </table> 

Java Script code:

  document.getElementById('abc').innerHTML = '<td id="bbc" style="color:yellow;">abc</td>' 

When I run the JS code in Firefox, it will change the display word from 'ccc' to 'abc', but it's just not working in IE8, does anyone know why? Is there any way I can make this work in IE8 as well?

like image 742
Jin Yong Avatar asked Aug 28 '09 00:08

Jin Yong


People also ask

Why innerHTML does not work?

People can struggle and complain about innerHTML not working. Such things usually occur because of human error, when strings are not appropriately defined, or there are some mistakes in JavaScript code.

What does document getElementById () innerHTML do?

getElementById("myPara") will return our html element as a javascript object which has pre-defined property innerHTML. innerHTML property contains the content of HTML tag.

How add HTML to innerHTML?

Using the innerHTML attribute: To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.


2 Answers

Since the problem is in IE8, see MSDN:

The property is read/write for all objects except the following, for which it is read-only: COL, COLGROUP, FRAMESET, HEAD, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR.

(emphasis mine)

Colin's work-around (setting innerText on the td instead of innerHTML on the tr) is a good one in your case. If your needs become more complex, you'll have to resort to The Table Object Model.

like image 85
Shog9 Avatar answered Sep 19 '22 18:09

Shog9


Since TR's innerHTML is read-only as a few people have said, you are better off changing your markup to target the TD:

<table><tr><td id="changeme"> ... </td></tr></table> 

Then you can set the content of the TD as you wish via innerHTML, and change other properties by setting them on the DOM node:

var td = document.getElementById("changeme"); td.innerHTML = "New Content"; td.cssText = "color: red"; td.className = "highlighted"; 

You get the idea...

This saves you the overhead of destroying and creating an extra DOM element (the TD)

like image 33
levik Avatar answered Sep 21 '22 18:09

levik