为什么不使用innerHTML_Why not use the innerHTML

记得上次被问过一个问题,为什么在给元素加入html代码的时候不使用innerHTML方法,而使用DOM操作,当时我的回答是,好像对支持有问题,似 乎只支持IE,但事实是真的目前所有浏览器都支持innerHTML方法,且HTML5的草案中也已经将其加入到DOM标准当中.但真的完美了吗,没有问 题了,一切OK?

DOM scripting当中有这样一段:
The innerHTML property can be quite useful when you want a quick and easy way to insert a chunk of HTML into a document. Unfortunately, innerHTML doesn’t return any references to the content you insert. If you want to manipulate the inserted content, you’ll need the precision offered by DOM methods.
You won’t be able to use it on any other kind of markup document. That means if you are serving up XHTML with the correct mime-type, innerHTML won’t work.
It’s also worth remembering that innerHTML is a proprietary method, not a web standard.

In any case, the standardized DOM can be used instead of innerHTML. It may take slightly more code to achieve the same results but, as you’ll see, it offers more precision and power.

不谈html代码过于难于精确控制的问题,也不谈其是不是标准的问题,由其最早是由ie使用可以得知,在非最高版本浏览器当中必定有对其不支持的问题存 在,而内容一定要完整呈现给用户,所以Backwards compatibility如果要做的话,必定要做方法可用性检测,所以对于innerHTML的使用我认为应该这样:
var testdiv = document.getElementById(“testdiv”);
if(testdiv.innerHTML){
testdiv.innerHTML = “html代码”;
}else{
var para = document.createElement(“p”);
testdiv.appendChild(para);
var txt = document.createTextNode(“Hello world”);
para.appendChild(txt);
}
由此可以达到最基本的向之前版本兼容的要求,且innerText,outHTML,outText同样适用。