IE6 the solution that the innerHTML of tbody cannot be assigned in IE9

  • 2020-03-30 03:14:39
  • OfStack

The innerHTML of tbody in IE6-IE9 cannot be assigned. The code for reproducing tbody is as follows
 
<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"/> 
<title>IE6-IE9 In the tbody the innerHTML Can't copy bug</title> 
</head> 
<body style="height:3000px"> 
<table> 
<tbody> 
<tr><td>aaa</td></tr> 
</tbody> 
</table> 
<p> 
<button id="btn1">GET</button><button id="btn2">SET</button> 
</p> 
<script> 
var tbody = document.getElementsByTagName('tbody')[0] 
function setTbody() { 
tbody.innerHTML = '<tr><td>bbb</td></tr>' 
} 
function getTbody() { 
alert(tbody.innerHTML) 
} 
btn1.onclick = function() { 
getTbody() 
} 
btn2.onclick = function() { 
setTbody() 
} 
</script> 
</body> 
</html> 

The first button gets the innerHTML of the tbody, and the second button sets the innerHTML of the tbody.

The tr string pops up in all browsers when getting, but ie6-9 is not supported when setting, and an error is reported, as shown
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201406/20140605153424.png? 20145515353 ">  
You can use the feature to see if the browser supports the innerHTML setting for tbody
 
var isupportTbodyInnerHTML = function () { 
var table = document.createElement('table') 
var tbody = document.createElement('tbody') 
table.appendChild(tbody) 
var boo = true 
try{ 
tbody.innerHTML = '<tr></tr>' 
} catch(e) { 
boo = false 
} 
return boo 
}() 
alert(isupportTbodyInnerHTML) 

If you want to set the innerHTML of tbody in ie6-ie9, you can use the following alternative
 
function setTBodyInnerHTML(tbody, html) { 
var div = document.createElement('div') 
div.innerHTML = '<table>' + html + '</table>' 
while(tbody.firstChild) { 
tbody.removeChild(tbody.firstChild) 
} 
tbody.appendChild(div.firstChild.firstChild) 
} 

A div is used to contain a table, and then all the elements in the tbody are deleted. Finally, the first element of the first element of div, namely div>, is added to the tbody. Table> The tr.

There is, of course, a more streamlined version that is directly replaced by the replaceChild method
 
function setTBodyInnerHTML(tbody, html) { 
var div = document.createElement('div') 
div.innerHTML = '<table>' + html + '</table>' 
tbody.parentNode.replaceChild(div.firstChild.firstChild, tbody) 
} 

The innerHTML of col, colGroup, frameset, HTML, head, style, table, tfoot, tHead, title, and tr are all read-only (ie6-ie9) as recorded on MSDN.

The innerHTML property is readable only on The col, colGroup, frameSet, HTML, head, style, table, tBody, tFoot, tHead, title, and tr objects.

You can change the value of the title element using the document.title property.

To change the contents of the table, tFoot, tHead, and tr elements, use the table object model described in Building Tables Dynamically. However, To change the content of a particular cell, You can use innerHTML.

Related articles: