Table innerHTML -- work around

zwq 2011-04-18

Asmanyofyoumusthavereadorrealised(idid)whileworkingwithit,MSInternetExplorerdoesn'tallowyoutosettheinnerHTMLpropertyofanytablerelatedtag(table,thead,tbody,trexceptfortd).Itsays"UnknownRuntimeException".Youareprovidedwithexplicitmethodstohandlethis.LikecreateRow,createCellandstuff...AlsoyoucanuseW3CDOMappendchild.

Goodwaytomaketables,butwhatifIhavetheTableHeaddefinedintheHTMLfileandreadtheTableBodyfromaXMLfileaswelldefinedstring.Isimplywanttohavethisinthetable...OnewayisIparsethestringasXMLandloopthroughthenodescreatingthecellsandsoon(thatiswhatIfirstdid),Butwhydoweneedthatunecessaryprocessing.Wedon'thaveanymethodtoparsethestringandgetintoourDOMdirectly.

TheworkaroundIworkedoutisprobablynottheonlyorbest,butworksgood.

supposewehaveavariablesXmlBodywhichhasallthetablebodyrowsdefinedlike:

varsXmlBody="<tr><td>cellOne1</td><td>cellTwo1</td><tr>"+

"<tr><td>cellOne2</td><td>cellTwo2</td><tr>";

Ofcourseitwillbecreateddynamically;)

NowtoaddthistotheDOMencloseitinactualtableandtbodytags.

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

andgetitinDOMparsedasHTMLusingatempdiv

vartempDiv=document.createElement("DIV");

tempDiv.innerHTML=sXmlBody;

NowIcanuseW3CDOMtoappendthechildfromthetempdivtothetableinourdocument.ConsidertheidofthetableintheHTMLdocumentidtableResults

vartableElement=document.getElementById("tableResult");

tableElement.appendChild(tempDiv.firstChild.firstChild);

Ifyouaregoingtoreloadthetablecontent,itwillbeusefultohaveanidforthetbodytaganduseremoveChildonthedocumentstablewiththetbodyelementasparameter.

Ihopethat'shelpfultoyouall,anditworksfineinFirefoxtoo!

TillNexttime...Happycoding

相关推荐

jiong / 0评论 2020-09-17