Warning: include_once(/home/kenv/kenvillines.com/wp-content/plugins/wordpress-support/wordpress-support.php): failed to open stream: Permission denied in /home/kenv/kenvillines.com/wp-settings.php on line 213

Warning: include_once(): Failed opening '/home/kenv/kenvillines.com/wp-content/plugins/wordpress-support/wordpress-support.php' for inclusion (include_path='.:/usr/local/lib/php:/usr/local/php5/lib/pear') in /home/kenv/kenvillines.com/wp-settings.php on line 213
» Using InnerHTML correctly within IE and Firefox Ken Villines 1.0

Using InnerHTML correctly within IE and Firefox

I have put this sample together so other programmers don’t run into the pitfalls I have.

Problem:
IE supports innerHTML for table cells and FireFox doesn’t.

Solution:
You have to embed a div within the table cell and perform all innerHTML calls on that. IE and FireFox both support this method.

Sample code below:

<html>
<head></head>
<body>
<script language="JavaScript">
<!--
/* This works for both IE and Firefox */
function toggleValue()
{
if(document.getElementById("currentItem").innerHTML != "1")
{
document.getElementById("currentItem").innerHTML = "1";
}else
{
document.getElementById("currentItem").innerHTML = "2";
}
}

//-->
</script>

<table width =" 200" border="0">
<tr>
<td colspan=2><br><center>
<a href="javascript:toggleValue()">Toggle Value</a>
</center></td>

</tr>
<tr>
<td>
<strong>Value:</strong>
</td><td>
<div id="currentItem">1</div>

</td>
</tr>
</table>
</body>
</html>

FireFox or IE Gotcha:
FireFox does not support table tags when changing the value of a div using innerHTML()- when the div is within a table cell. Form tags along with most other tags are supported

*IE does support table tags when changing the value of a div using innerHTML() when the div is within a table cell.

I am not really sure who is right and who is wrong with the Gotcha…

32 Responses to “Using InnerHTML correctly within IE and Firefox”

  1. Joe Ravgiala Says:

    Thanks Ken, This helped out alot.

    Joe

  2. Ken Villines Says:

    No problem…Looking into the different problems was fun!

    Take care
    -Ken

  3. Bill Lubanovic Says:

    If you move the toggleValue() code to the HEAD area, then it works for TD tags in Firefox. I’d love to know why.

    Bill

  4. osvaldo Says:

    This script don’t work in firefox all vertions. cant helpme

    Osvaldo fron Asunción

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
    <html xmlns="http://www.w3.org/1999/xhtml"&gt;
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    </script>
    <noscript>
    Su navegador no soporta JavaScript
    </noscript>
    <script language="JavaScript1.1" type="text/javascript">
    function dateMessage()
    {var special_days=new Array();

    //******************************************************
    // Add dates and messages here. Add as many as you like.
    //******************************************************

    special_days[0]=new Array(‘&bull; Norma Liliana Adle Roman <br /> &bull; Bruce Burnett <br /> &bull; Marcelo Alejandro Chiquetti Redala <br /> &bull; Marcos Lacarrubba <br /> &bull; Andre De Oliveira <br/> &bull; Paulo De Souza <br /> &bull; Celso Duarte Velazquez <br /> &bull; Guillermo Franco Fleitas <br /> &bull; Karen Rocio Ortiz Paiva <br /> &bull; Ana Paula Pereira De Souza <br /> &bull; Maricel Rodriguez Baez Sabatini <br /> &bull; Luis Fernando Zarza Albertini <br /> &bull; Sanie Sardi Salazar <br /> &bull; Patricia Raquel Benitez Quevedo <br /> &bull; Fernando Chiriani <br /> &bull; Maria Leticia Navarro Vergara <br /> &bull; Maria Del Carmen Vera Del Puerto <br /> &bull; Diego Marcelo Minardi Caceres <br /> &bull; Carlos Jorge Mendez Cardozo <br /> &bull; Luis Alberto Lavigne Bueno <br /> &bull; Oscar Victor Britez Arga&ntilde;a <br /> &bull; Paulo Roberto Rodriguez’,’9/22/2005′);
    special_days[1]=new Array(‘&bull; Marco Antonio Bordon Riveros <br />&bull; Mariela Olivia Barboza Barboza <br />&bull; Gabriela Maria Chiriani Gamarra <br />&bull; Diego Cha&ntilde;ar Bejarano Barreto <br />&bull; Claudia Edith Gamarra Lezcano <br />&bull; Alberto Gross Brown <br />&bull; Patricia Elizabeth Gauto Bogado <br />&bull; Luis Guillen Llano <br />&bull; Leticia Fernandez Guggiari <br />&bull; Mario Luis Ortellado Baez <br />&bull; Claudia Leticia Pozzoli Cuevas <br />&bull; Maria Laura Orue <br />&bull; Gabriela Miracca Sarubbi <br />&bull; Juan Carlos Ricciardi <br />&bull; Erika Von Zastrow <br />&bull; Pamela Bernal Dos Santos <br />&bull; Gabriela Davalos Fernandez <br />&bull; Jazmin Venialgo Rossi <br />&bull; Christian Eduardo Amarilla Lizan <br />&bull; Mauricio Alfaro <br />&bull; Arnaldo Macoritto Aquino <br />&bull; Ivan Jose Albertini Baumgarten <br />&bull; Francisco Javier Riquelme Irun <br />&bull; Diego Prayones’,’9/23/2005′);

    //******************************
    // Don’t edit below here
    //******************************

    var now=new Date();
    var m=now.getMonth()+1;
    var d=now.getDate();
    var y=now.getYear();
    var dt=m+"/"+d+"/"+y;

    for(var i=0;i<special_days.length;i++)
    {
    if(special_days[i][1]==dt)
    {
    var str=special_days[i][0];
    }
    }

    document.all['msg'].innerHTML=str;
    // document.getElementById(‘msg’).innerHTML=str;
    }
    </script>

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <link href="cumples.css" rel="stylesheet" type="text/css">
    </head>
    <body bgcolor="#000000" text="#CCCCCC" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" onLoad="dateMessage();MM_callJS(‘dateMessage()’)">
    <span id="msg" class="TXT10px"> </span>

    </body>
    </html>

  5. Ken Villines Says:

    @ Bill

    This is very interesting. I am going to have to try this and then report the issue through Bugzilla.

    Nice Catch!

  6. Ken Villines Says:

    @ Osvaldo

    I will take a look as soon as possible.

    -Ken

  7. Danilo Soares Aliberti Says:

    Uhhhuuuuu, thanx a lot! It it’s simple. Like all the solution have to be!

    Thanx again!

  8. Jerome Says:

    IE and Firefox have a different treatment for innerHTML on DIV tags…

    if you do:
    Node.innerHTML = “”;

    Firefox seems to makes the node =

    IE seems to put a   in the node
    so it keeps taking space

    if you do:
    Node.innerHTML = null;

    again Firefox seems to makes the node =

    IE seems to makes the node = NULL

  9. Ben Keen Says:

    This certainly helped, but it doesn’t appear to work in every case – or else I’ve encountered a similar, but different problem.

    The URL I’ve included links to a little program I’m developing for mass producing random data (the code’s actually done, I’m just adding the DHTML interface).

    A problem occurs when I use innerHTML to set the contents of a (which is now a , thanks to your article!). The problem is that sometimes when you select the Data Type option of “Text: Fixed Number of Words”, the content that is innerHTMLed into the Options column for the row messes up the table formatting, due to it having a different height from the other rows.

    Try messing around with it. See what I mean? It doesn’t appear to happen consistently, which is the real stinker. IE, for once, appears to be working fine.

  10. Ben Keen Says:

    Fixed! If anyone else encounters this problem, I fixed it by wrapping the innerHTML command in a setTimeout. That seems to help the table render properly. Odd!

  11. Ken Villines Says:

    @Ben

    hmmm Interesting…Did you actually pass in a timeout? it is probably an order of operation issue or scoping issue in the DOM.

    I don’t know if you took your site down but I am getting a blank page when I try to view your app.

    -Ken

  12. Pablo Cuadrado Says:

    This is VERY simple:

    Cell 1Cell 2Cell 3

    // Doesn’t works in IE.
    var theInner = document.getElementById(“someTable”).rows[0].innerHTML;
    var newRow = document.getElementById(“someTable”).tBodies[0].insertRow(1);
    // And here it crashes…
    document.getElementById(“someTable”).tBodies[0].rows[1].innerHTML = theInner;

    Anyone?

  13. Pablo Cuadrado Says:

    I couldn’t post my previous comment. How do I post a comment with HTML markups on it?

  14. Hamish Dean Says:

    Works in IE and Firefox if u remove the XHTML tags that Dreamweaver automatically adds in.
    Hope this helps in some way.

  15. Ryoz Says:

    Nice topic, very very helpful.

  16. Bruno Bernardino Says:

    I solved the problem in FireFox 1.5.2 by replacing

    document.all.(‘id’).innerHTML = somevar

    with

    document.getElementById(‘id’).innerHTML = String(somevar);

    it seems FireFox gets troubled because innerHTML has to be a string? weird anyways…

    Hope this helps…

  17. Rajiv Says:

    str1=
    new Draggable(’2′, {revert:true})

    document.getElementById(“div1″).innerHTML=str1;

    when i am tring to add above string in a div tag

    image and script is working in IE,but not in Mozilla Firefox

    Any one.

  18. Rajiv Says:

    str1=img class=’products’ id=’2′ src=’images/logo1.gif’ style=’position:relative;’
    script type=’text/javascript’ defer=’defer’ new Draggable(’2′, {revert:true})script

    document.getElementById(“div1″).innerHTML=str1;

    when i am tring to add above string in a div tag

    image and script is working in IE,but not in Mozilla Firefox

    Any one.

  19. Dec Says:

    A table can work in getElementById by changing to %3E

    try the following…

    function encodeMe(a)
    {
    // This will make a table work in firefox
    var plaintext = a;
    var encoded = “”;
    for (var i = 0; i ‘){
    encoded += ‘%3E’;
    }else{
    encoded += plaintext[i];
    }

    }

    return encoded;
    };

    document.getElementById(“txtarea”).innerHTML = encodeMe(“Hello)”;

  20. Thierry Says:

    Just read that IE doesn’t support innerHTML on the table and the rows itselve. You CAN read the content, but you can’t edit it’s content.
    It would have been great when IE just worked the same as FF *sigh* :(

  21. babas Says:

    The technic of using a div however is buggy as it does not update properly (in the DOM) the cell.
    In order to fix the innerHTML in cell (TD) for firefow use the following code.

    oMycell //dom cell , can be retrieved using getElementByID
    oRow = oMycell.parentNode
    t = oRow .offsetHeight;
    oRow .offsetHeight = t;

    This works fine for me.

  22. xprienced Says:

    Hamish is correct . Remove the XHTML tag by DW and you will get it working in Firefox. It took my 3 hrs and then just a suggestion of Xhtml worked.

    Zindagi ROcks.

  23. krrcwl Says:

    I’ve come across a strange bug in Firefox; I’m using the usual AJAX method to pull in some HTML to put into a Div, which contains two tables, the first of which displays fine, but the second doesn’t. The DOM Inspector correctly shows the bounds of the second table, but all its the contents (some radio buttons and selects) are just not displayed.

    I have been using Safari to test with and all is fine there. I haven’t dared try it on IE yet!

    If anyone has any ideas? …

  24. krrcwl Says:

    Ach, eventually I discovered it was a caching issue. Firefox wasn’t doing a fresh reload with Command-Option-R, so it was still working from a broken version. Had to clear the cache explicitly. Strange.

  25. Tinhvd Says:

    Hi all!
    I have a problem!
    Why using innerHTML in IE be reload page jsp, while firefox no!

    Thanks!

  26. Venkat Says:

    Thanks a Lot…

  27. Sean and Risa Says:

    Ken,

    Thank you for the tips. You saved us from the pitfall.

    Regards,

  28. ManFree Says:

    Respond to the -> “Remove the XHTML tag by DW and you will get it working in Firefox.”

    I have removed the XHTML tag … but the innerHTML still not working in FireFox …. (it works in IE)

  29. Bigtema Says:

    Thank you! That helps me a lot.

    Best regards from Russia.

  30. rey Says:

    When I test this one on firefox and its OK, when I test it on IE and its not functional… Can anyone help me with this!? but when I test on the other computer it works on IE4+…

    function GetXmlHttpObject(handler){
    var objXMLHttp=null
    if (window.XMLHttpRequest){
    objXMLHttp=new XMLHttpRequest()
    }else if (window.ActiveXObject){
    objXMLHttp=new ActiveXObject(“Microsoft.XMLHTTP”)
    }
    return objXMLHttp
    }
    function builderChanged(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState==”complete”){
    document.getElementById(‘vill’).innerHTML= xmlHttp.responseText;
    }
    }
    function htmlDataBuilder(url, qStr){
    if (url.length==0){
    document.getElementById(“vill”).innerHTML=”";
    return;
    }
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null){
    alert (“Browser does not support HTTP Request”);
    return;
    }

    url=url+”?”+qStr;
    url=url+”&sid=”+Math.random();
    xmlHttp.onreadystatechange=builderChanged;
    xmlHttp.open(“GET”,url,true) ;
    xmlHttp.send(null);
    }

  31. Pritam Paul Says:

    You are great, this worked for me. Even using to DOJO AJAX this worked well.

  32. raja Says:

    thank you, simple solution but really great.

Leave a Reply