Outer Court

Tech - DOM/ DHTML - Tables

Note that the table element contains a TBODY element which you don't use if you write HTML. However it's needed in DOM and actually there in IE. You can see it for example when you give out the source by the use of innerHTML. So, a typical table would be:


<table>
<tbody>
<tr>
  <td>The first child of parent "tr"</td>
  <td>The second and last child of the parent node.
      The sibling of the previous "td"</td>
</tr>
</tbody>
</table>




(The relations are referring to the cell, not the textual content of it).

Building a table

Build a table with x and y variables (the range are the tableY and tableX values). Each cell contains a paragraph with "[Sampletext]"


  elmTable = document.createElement( "table" );
  elmTbody = document.createElement( "tbody" );

  for (y = 1; y <= tableY; y++)
  {
    elmTr = document.createElement( "tr" );

    for (x = 1; x <= tableX; x++)
    {
      elmTd = document.createElement( "td" );
      elmP = document.createElement( "p" );
      elmTxt = document.createTextNode( "[Sampletext]" );
      elmP.appendChild( elmTxt );
      elmTd.appendChild( elmP );
      elmTr.appendChild( elmTd );
    }
  
    elmTbody.appendChild( elmTr );
  }

  elmTable.appendChild( elmTbody );




You could make a function and return "elmDiv" as an element which you could then append to the body or something. Note the scope of the elm-objects: For example TD is contained only within the x loop, while TR stays alive through-out it (to "collect" all the needed TD's).
Here the element's are given as lower-case strings, but my experience is they are converted to upper-case immediately, so if you want to refer to them (like test the nodeName property), use upper-case (even though XHTML-tags must be lowercase since XML is case-sensitive).

Excel-Import

Convert CSV ("text"-parameter) to HTML-String:

function convertCVStoHTM(text)
{
  var strTable = "", seperator = ";";

  if (text! = "")
  { if ( text.substring(text.length-2,text.length-1) =  = "\r" )
      text = text.substring(0,text.length-2);
    strTable = "<table><tr><td><p>\r\n";
    strTable+ = replStr(text,"\r","</p></td></tr>\r\n<tr><td><p>");
    strTable = replStr(strTable,seperator,"</p></td><td><p>");
    strTable+ = "</p></td></tr></table>";
  }
  return strTable;
}



Well, actually this returns a string and no DOM object. Insertable with innerHTML. Note: You need function replStr() for this to work (a recursive string replacer):

function replStr(str,oldStr,newStr)
{ var strPos=str.indexOf(oldStr);
  return (strPos>=0) ?
    str.substring(0,strPos) + newStr +
       replStr( str.substring(strPos +
       oldStr.length), oldStr, newStr ) :
    str
}



 

 
Basic
Goodies
Design
Tech
Email
Make a donation