zoukankan      html  css  js  c++  java
  • Table innerHTML work around

    As many of you must have read or realised(i did) while working with it, MS Internet Explorer doesn't allow you to set the innerHTML property of any table related tag(table, thead, tbody, tr except for td). It says "Unknown Runtime Exception". You are provided with explicit methods to handle this. Like createRow, createCell and stuff... Also you can use W3C DOM append child. 

    Good way to make tables, but what if I have the Table Head defined in the HTML file and read the Table Body from a XML file as well defined string. I simply want to have this in the table... One way is I parse the string as XML and loop through the nodes creating the cells and so on (that is what I first did), But why do we need that unecessary processing. We don't have any method to parse the string and get into our DOM directly. 

    The work around I worked out is probably not the only or best, but works good. 

    suppose we have a variable sXmlBody which has all the table body rows defined like: 

    var sXmlBody = "<tr><td>cellOne1</td><td>cellTwo1</td><tr>" + 
    "<tr><td>cellOne2</td><td>cellTwo2</td><tr>" ; 


    Of course it will be created dynamically ;) 

    Now to add this to the DOM enclose it in actual table and tbody tags. 

    sXmlBody = "<table><tbody>" + sXmlBody + "</tbody></table>"; 

    and get it in DOM parsed as HTML using a temp div 


    var tempDiv = document.createElement("DIV"); 
    tempDiv.innerHTML = sXmlBody; 

    Now I can use W3C DOM to append the child from the temp div to the table in our document. Consider the id of the table in the HTML document id tableResults 


    var tableElement = document.getElementById("tableResult"); 
    tableElement.appendChild(tempDiv.firstChild.firstChild); 

    If you are going to reload the table content, it will be useful to have an id for the tbody tag and use removeChild on the documents table with the tbody element as parameter. 

    I hope that's helpful to you all, and it works fine in Firefox too! 

    Till Next time . . . Happy coding

  • 相关阅读:
    Jquery简略API使用
    JS全部API笔记
    实现nginx的负载均衡和反向代理
    HashMap在Java1.7与1.8中的区别
    数据库设计三大范式
    Java集合
    Object类有哪些方法
    spring mvc出现 Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'endtime'
    int和Integer的区别
    第二次面试-科大讯飞(卒)
  • 原文地址:https://www.cnblogs.com/zhuqiang/p/2484990.html
Copyright © 2011-2022 走看看