开发者

How to clean up divs contents?

I heared that simply to say document.getElementById('divId').innerHTML = ""; is not safe for future divId contents editing via JS开发者_运维技巧 so how to clean up divs contents safely?


What should always work is:

var div = document.getElementById('divId');
while(div.hasChildNodes()) {
    div.removeChild(div.firstChild);
}

innerHTML is not part of any specification but is widely supported by browsers.


I wrote something similar to Felix Kling, only diffirence is that I wanted to pass the id or the reference. So I wrote it like this:

function removeAllChildNodes(node) {
    i = (typeof(node) == "object") ? node : document.getElementById(node);

    while (i.hasChildNodes()) {
        i.removeChild(i.firstChild);
    }
}


Setting the innerHTML attribute to nothing will eliminate any DOM nodes withing the specified DIV. There is no risk of "safety".

You can do this safely :P


I believe this is where JS frameworks, such as jQuery, come to light... they are optimized for cross-browser security - which includes secure DOM element removal, although you will loose a bit of computing speed (setting innerHTML is always the fastest way)

as for others wondering about security of this, some browsers (notably MSIE) have flaws that would crash the browser or allow malicious procedures to be executed on client's side under certain conditions, so that's why setting innerHTML might not be as secure as people use to think ;-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜