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

  • 相关阅读:
    【MyBatis】学习笔记010--#{}与¥{}的区别
    【MyBatis】学习笔记009--基于注解的CRUD
    【MySQL】limit语法
    【MyBatis】学习笔记008--分页查询
    【MyBatis】学习笔记007--日志工厂
    【MyBatis】学习笔记006--resultMap简单结果映射
    【MyBatis】学习笔记005--生命周期与作用域
    【MyBatis】学习笔记004--XML配置
    重学动态规划
    剑指 Offer 09. 用两个栈实现队列
  • 原文地址:https://www.cnblogs.com/zhuqiang/p/2484990.html
Copyright © 2011-2022 走看看